【发布时间】:2011-09-12 16:14:03
【问题描述】:
我正在传递一个指向函数的指针,并且我想在被调用函数中初始化结构数组并想使用该数组主函数。但是我无法在主要功能中使用它。 这是我的代码:
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;
}
请注意,我必须根据需要将双指针传递给函数。 感谢您的帮助。
【问题讨论】:
-
这看起来像是几段不相关的代码的随机重新散列。在
main函数中,数组显然是一维的。然而,allocate中的代码显然是从分配二维数组的尝试中复制而来的。那么,您要分配的是什么?一维数组?还是二维数组?你需要先做出决定。
标签: c pointers multidimensional-array