Search code examples
carrayspointersstructabstract-data-type

Creating array of pointers to struct inside a struct


Basiclly, I have a struct defined this way:

struct D_Array
{
    int Capacity;
    int Cur_Size;
    struct Student* List;
};

Now, after creating the struct;

struct D_Array* T_Array;
if (T_Array = malloc(sizeof(struct D_Array)) == NULL)
{
    printf("There has been a problem with memory allocation. Exiting the program.");
    exit (21);
}

I have a problem creating the students list inside this struct. I need the list to be an array of pointers, since I should make some kind of ADT program, I've tried to make it something like this:

T_Array->Capacity = 10;
T_Array->Cur_Size = 0;
T_Array->List[10]= (struct Student*) malloc(sizeof (struct Student*));

It doesn't matter how I tried to change it, I'm getting the same error: incompatible types when assigning to type 'struct Student' from type 'struct Student *'|

I've trying to create an array that I will be able to do something like;

T_Array->List[1]=Student_Pointer;

Thanks!


Solution

  • Change the type of the array to struct Student** that will be array of pointers :

    struct student * --> a pointer to student. struct student ** --> a pointer to a pointer to student (what you need).

    struct D_Array
    {
        int Capacity;
        int Cur_Size;
        struct Student** List;
    }
    

    and the allocation:

    T_Array->List = malloc (sizeof (struct Student*) *  lengthofarray);
    

    and then:

    T_Array->List[1]=Student_Pointer;