【问题标题】:Unable to get array of structures initialized无法初始化结构数组
【发布时间】: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


【解决方案1】:
#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; 
}

应该可以。

【讨论】:

  • 谢谢 Ed Heal,你救了我的夜晚 :)
【解决方案2】:
t = (testStruct**)malloc(10 * sizeof(testStruct));

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

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

相反?我不确定,当周围有这么多指针时,我往往会迷路。无论如何,您似乎没有为传递给函数的指针分配任何内容。

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2015-07-29
      • 1970-01-01
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-02
      相关资源
      最近更新 更多