无法初始化结构数组

时间:2011-09-12 16:14:04

标签: c pointers multidimensional-array

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

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;
}

请注意我必须将双指针传递给函数,因为它是必需的。 谢谢你的帮助。

3 个答案:

答案 0 :(得分:0)

t = (testStruct**)malloc(10 * sizeof(testStruct));

分配给t,而不是test。也许你想要

*t = (testStruct*)malloc(10 * sizeof(testStruct));

代替?我不确定,当有这么多指针时,我往往会迷失方向。无论如何,您似乎没有将任何内容分配给传递给函数的指针。

答案 1 :(得分: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; 
}

应该工作。

答案 2 :(得分:0)

你说你想要创建一个结构数组,但是你的allocate函数创建的数据结构更像是二维数组。此外,您不会以任何有意义的方式将该结构返回给调用者。我认为你对指针malloc()以及你正在做的所有间接方面感到困惑。查看@Ed Heal对更正程序的回答。