0

I have a struct with an int array inside that I'm passing to a function for the array to be initialized

array struct like so..

typedef struct Container{
    struct intArray *P;
    int length;
} Container;

typedef struct intArray{
    int *array;
    int length;
} intArray;

function to initialize the array like so...

int Initializer(intArray *myStruct, int n)
{
    myStruct->array = malloc(sizeof(int) * (lengthOfint);
                                              ^
                                        If n=55 then length would be 2
    //let's just say n=5
    myStruct->array[0] = n;

    //return 1 if successful
    return 1;
}

In another function I am calling the initializer function like so...

Container *myContainer = malloc(sizeof(Container));

myContainer->P = malloc(sizeof(intArray *) * Some_Defined_Value);

Initializer(&myContainer, 5);

printf("the data that should be at index 0 -> %d\n", myContainer->P.array[0];

I would think that the printf statement would print out 5 but it prints out garbage of varying numbers every time I compile it. I don't think I have a grasp of the array within a struct within a struct idea.

4

3 回答 3

1

您将容器传递给初始化函数,但如果仔细观察,您会发现您传递的是指向“外部”容器的指针,而不是指向所需的指针struct intArray。你想要类似的东西Initializer(myContainer->P, 5);

于 2013-06-12T23:30:51.310 回答
0

另请注意,malloc返回 avoid *所以大多数时候您需要像这样的演员表:

myStruct->array = (int*)malloc(sizeof(int) * (length);
//                ^^^^^^

假设length是您要存储在数组中的 int 数量。

于 2013-06-12T23:43:54.630 回答
0

Container持有指向 的指针struct intArray,在本例中是 的数组的开头struct intArray。但是然后你初始化这个指针

malloc(sizeof(intArray *) * Some_Defined_Value);

因此 malloc 返回一个指向内存空间的指针,该内存空间保存指向的指针struct intArray因为您使用sizeof(intArray *)而不是(您为指针数量sizeof(intArray)分配了空间)。Some_Defined_Value

您需要在这里为's的数量sizeof(intArray) * Some_Defined_Value分配空间。Some_Defined_Valuestruct intArray

然后你使用

Initializer(&myContainer, 5);

这至少应该给出一个警告,因为你传递了一个指向a 的指针struct Container,但Initializer需要一个指向a的指针,struct intArray所以这不是你想要的。要初始化 ' 数组的第一个元素,请struct intArray使用:

Initializer(&(myContainter->P[0]), 5);

然后:

printf("the data that should be at index 0 -> %d\n", myContainer->P.array[0]));

此代码无法编译,因为它应该是:

printf("the data that should be at index 0 -> %d\n", myContainer->P[0].array[0]);

myContainer->P访问指向 a的指针struct intArray。上面的代码意味着您访问struct intArray's 数组的第一个元素(元素编号 0)。

要初始化/访问数组的第二个元素,请struct intArray使用:

Initializer(&(myContainter->P[1]), 5);
printf("the data that should be at index 0 -> %d\n", myContainer->P[1].array[0]);
于 2013-06-13T00:28:11.117 回答