[英]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”並且幸運的是程序沒有中止(或者它中止了,這就是沒有輸出的原因)。
Ps:完成后不要忘記釋放內存:
for (index=0; index<10; index++)
free(mystruct->myarray[index]);
free(mystruct);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.