gpt4 book ai didi

c - 无法初始化结构数组

转载 作者:行者123 更新时间:2023-11-30 18:04:46 25 4
gpt4 key购买 nike

我正在传递一个指向函数的指针,我想初始化被调用函数中的结构数组,并想使用该数组主函数。但我无法在主函数中获取它。这是我的代码:

typedef struct _testStruct
{
int a;
int b;
} testStruct;

void allocate(testStruct** t)
{
int nCount = 0;
int i = 0;
printf("allocate 1\n");
t = (testStruct**)malloc(10 * sizeof(testStruct));
for(i = 0; i < 10; i++)
{
t[i] = (testStruct *) malloc( 10 * sizeof(testStruct));
}
for(nCount = 0 ; nCount < 10; nCount++)
{
t[nCount]->a = nCount;
t[nCount]->b = nCount + 1;

printf( "A === %d\n", t[nCount]->a);
}

}
int main()
{
int nCount = 0;
testStruct * test = NULL;
int n = 0;
allocate(&test);
for(nCount = 0 ; nCount < 10; nCount++ )
{
if (test == NULL)
{
printf( "Not Allocated\n");
exit(0);
}
//printf("a = %d\n",test[nCount]->a);
/*printf("a = %d\n",test->a);
printf("b = %d\n",test->b); */
}

return 0;
}

请注意,我必须根据需要将双指针传递给函数。感谢您的帮助。

最佳答案

#include <stdio.h>
#include <stdlib.h>

typedef struct _testStruct
{
int a;
int b;
} testStruct;

void allocate(testStruct** t)
{
int nCount = 0;
printf("allocate 1\n");
testStruct *newT = (testStruct*)malloc(10 * sizeof(testStruct));
for(nCount = 0 ; nCount < 10; nCount++)
{
newT[nCount].a = nCount;
newT[nCount].b = nCount + 1;

printf( "A === %d\n", newT[nCount].a);
}

*t = newT;

}
int main()
{
int nCount = 0;
testStruct * test = NULL;
allocate(&test);
for(nCount = 0 ; nCount < 10; nCount++ )
{
printf("a = %d\n",test[nCount].a);
printf("a = %d\n",test[nCount].b);

}

return 0;
}

应该可以。

关于c - 无法初始化结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7390863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com