加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

数组在C结构

发布时间:2020-12-16 05:38:35 所属栏目:百科 来源:网络整理
导读:我想在一个结构体中有两个数组,它们在开始时被初始化,但需要进一步编辑.我需要三个结构的实例,所以我可以索引到一个特定的结构,并按照我的意愿修改.可能吗? 这是我以为我可以做但我得到错误: struct potNumber{ int array[20] = {[0 ... 19] = 10}; char *
我想在一个结构体中有两个数组,它们在开始时被初始化,但需要进一步编辑.我需要三个结构的实例,所以我可以索引到一个特定的结构,并按照我的意愿修改.可能吗?

这是我以为我可以做但我得到错误:

struct potNumber{
    int array[20] = {[0 ... 19] = 10};
    char *theName[] = {"Half-and-Half","Almond","Rasberry","Vanilla",…};
} aPot[3];

然后我访问结构如下:

printf("some statement %s",aPot[0].array[0]);
 aPot[0].theName[3];
 …

解决方法

结构本身没有数据.您需要创建struct类型的对象并设置对象…
struct potNumber {
    int array[20];
    char *theName[42];
};

/* I like to separate the type definition from the object creation */
struct potNumber aPot[3];
/* with a C99 compiler you can use 'designated initializers' */
struct potNumber bPot = {{[7] = 7,[3] = -12},{[4] = "four",[6] = "six"}};

for (i = 0; i < 20; i++) {
  aPot[0].array[i] = i;
}
aPot[0].theName[0] = "Half-and-Half";
aPot[0].theName[1] = "Almond";
aPot[0].theName[2] = "Rasberry";
aPot[0].theName[3] = "Vanilla";
/* ... */

for (i = 0; i < 20; i++) {
  aPot[2].array[i] = 42 + i;
}
aPot[2].theName[0] = "Half-and-Half";
aPot[2].theName[1] = "Almond";
aPot[2].theName[2] = "Rasberry";
aPot[2].theName[3] = "Vanilla";
/* ... */

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读