c - C 结构中的数组

标签 c arrays struct

我想在一个结构中有两个数组,它们在开始时被初始化但需要进一步编辑。我需要该结构的三个实例,以便我可以索引到特定结构并根据需要进行修改。可能吗?

这是我认为我可以做的,但我得到了错误:

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 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";
/* ... */

关于c - C 结构中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5170525/

相关文章:

python - 堆叠稀疏和密集矩阵

javascript - 如何从数组数组中创建一个新数组,仅选择具有所需索引的元素

c - C 中的动态字符串数组结构

c++ - 为什么C++中的成员类要先初始化?

C++ 链表指针指向结构崩溃

可以从编译时未知的其他地方修改 const 变量吗

c - 使用另一个 char 数组从 struct 设置一个 char 数组

无法在 C 中初始化大型二维数组

c - 如何正确使用fwrite?

javascript - 数组数组的 JS 子集