C结构中的数组

Gre*_*eg 14 c arrays struct

我想在一个struct中有两个数组,它们在start时初始化但需要进一步编辑.我需要三个结构实例,以便我可以索引到一个特定的结构并按我的意愿修改.可能吗?

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

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

然后我按如下方式访问结构:

 printf("some statement %s", aPot[0].array[0]);
 aPot[0].theName[3];
 …
Run Code Online (Sandbox Code Playgroud)

pmg*_*pmg 14

结构本身没有数据.您需要创建结构类型的对象并设置对象...

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";
/* ... */
Run Code Online (Sandbox Code Playgroud)


dat*_*olf 9

在C struct数组元素必须具有固定大小,因此char *theNames[]无效.此外,您无法以这种方式初始化结构.在C数组中是静态的,即不能动态地改变它们的大小.

结构的正确声明如下所示

struct potNumber{
    int array[20];
    char theName[10][20];
};
Run Code Online (Sandbox Code Playgroud)

你初始化它像这样:

struct potNumber aPot[3]=
{
    /* 0 */
    { 
        {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 /* up to 20 integer values*/ },
        {"Half-and-Half", "Almond", "Raspberry", "Vanilla", /* up to 10 strings of max. 20 characters */ }
    },
    /* 1 */
    { 
        {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 /* up to 20 integer values*/ },
        {"Half-and-Half", "Almond", "Raspberry", "Vanilla", /* up to 10 strings of max. 20 characters */ }
    },
    /* 2 */
    { 
        {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10 /* up to 20 integer values*/ },
        {"Half-and-Half", "Almond", "Raspberry", "Vanilla", /* up to 10 strings of max. 20 characters */ }
    }
};
Run Code Online (Sandbox Code Playgroud)

但是,我很确定这不是你想要的.理解这种方法需要一些样板代码:

struct IntArray
{
    size_t elements;
    int *data;
};

struct String
{
    size_t length;
    char *data;
};

struct StringArray
{
    size_t elements;
    struct String *data;
};
/* functions for convenient allocation, element access and copying of Arrays and Strings */

struct potNumber
{
    struct IntArray array;
    struct StringArray theNames;
};
Run Code Online (Sandbox Code Playgroud)

我个人强烈建议不要使用裸C阵列.通过辅助结构和函数执行所有操作可以使您从缓冲区/溢出和其他问题中清除.每个严肃的C编码器都会随着时间的推移建立一个像这样的东西的替代金库代码库

  • 好的,谢谢你的帮助,你能给我一个如何输入数据的例子,以及我如何能够访问它? (2认同)