访问动态分配的结构内部数组中的元素
Accessing Element in Array Inside Struct Dynamically Allocated
所以我有一个结构数组,每个结构都包含一个动态字符串数组。
typedef struct _test {
int total;
char *myarray[];
} Test;
这是我分配足够内存的方式
Test *mystruct = (Test *)malloc(size);
以上是我的结构的格式
mystruct[x].myarray[index] = strdup(name);
index++;
mystruct[x].total = index;
尝试访问该数组中的字符串时,即:
printf("%s", mystruct[0].myarray[0]);
没有打印出来,感谢您的帮助!
以下是正确的。我会在下面解释。
typedef struct TEST {
int total;
char *myarray[];
} Test;
int StackOveflowTest(void)
{
int index;
Test *mystruct = malloc(sizeof(Test)+10*sizeof(char *));
for (index=0; index<10; index++)
mystruct->myarray[index] = strdup("hello world");
mystruct->total = index;
for (index=0; index<10; index++)
printf("%s\n", mystruct->myarray[index]);
return 0;
}
实际上,您声明了一个“指针数组”myarray
,但是该数组有零个元素。这个“技巧”用于在结构的末尾具有可变大小的数组,当 malloc
'ing 数组时:
Test *mystruct = malloc(sizeof(Test)+10*sizeof(char *));
这会分配结构的大小并为 10 个数组元素增加空间。
由于您没有分配结构的这个灵活部分,所以您写入了“nothing”并且幸运的是程序没有中止(或者中止了,这就是没有输出的原因)。
P.s.: 完成后别忘了释放内存:
for (index=0; index<10; index++)
free(mystruct->myarray[index]);
free(mystruct);
所以我有一个结构数组,每个结构都包含一个动态字符串数组。
typedef struct _test {
int total;
char *myarray[];
} Test;
这是我分配足够内存的方式
Test *mystruct = (Test *)malloc(size);
以上是我的结构的格式
mystruct[x].myarray[index] = strdup(name);
index++;
mystruct[x].total = index;
尝试访问该数组中的字符串时,即:
printf("%s", mystruct[0].myarray[0]);
没有打印出来,感谢您的帮助!
以下是正确的。我会在下面解释。
typedef struct TEST {
int total;
char *myarray[];
} Test;
int StackOveflowTest(void)
{
int index;
Test *mystruct = malloc(sizeof(Test)+10*sizeof(char *));
for (index=0; index<10; index++)
mystruct->myarray[index] = strdup("hello world");
mystruct->total = index;
for (index=0; index<10; index++)
printf("%s\n", mystruct->myarray[index]);
return 0;
}
实际上,您声明了一个“指针数组”myarray
,但是该数组有零个元素。这个“技巧”用于在结构的末尾具有可变大小的数组,当 malloc
'ing 数组时:
Test *mystruct = malloc(sizeof(Test)+10*sizeof(char *));
这会分配结构的大小并为 10 个数组元素增加空间。
由于您没有分配结构的这个灵活部分,所以您写入了“nothing”并且幸运的是程序没有中止(或者中止了,这就是没有输出的原因)。
P.s.: 完成后别忘了释放内存:
for (index=0; index<10; index++)
free(mystruct->myarray[index]);
free(mystruct);