Search code examples
cpointersmallocdynamic-arrays

C: Incompatible type on dynamic array of pointers of structure


I need help to declare a dynamic array of pointers. A read some articles and similar questions about it and I try to do it for my project but still frozen.

What I'm trying to do:

typedef struct recArmario Armario, *pArmario;

struct recArmario {
    int ID;
    pArmario next;
    pArmario prev;
    pCorredor parent;
};

pArmario auxArmarioTest1 = malloc(sizeof(Armario));
auxArmarioTest1->ID = 1;
pArmario auxArmarioTest2 = malloc(sizeof(Armario));
auxArmarioTest2->ID = 2;

(…)

//Dynamic array of pointer Armario:
pArmario arrArmariosPointers = malloc(sizeof(pArmario) * maxCorredores);
//Here is my doubt
*(arrArmariosPointers + idCorredor) = auxArmarioTest1;

Xcode is saying:

Assigning to 'struct recArmario' from incompatible type 'pArmario' (aka 'struct recArmario *'); dereference with *

I don't understand, "Assigning to 'struct recArmario'"?! I declare one array of pArmario, I think so.

*(arrArmariosPointers + idCorredor) is equivalent to arrArmariosPointers[idCorredor], right?

UPDATE 1:

Thanks for the answers! I update my sample and still have problems.

pArmario auxArmarioTest1 = malloc(sizeof(Armario));
auxArmarioTest1->ID = 1;
pArmario auxArmarioTest2 = malloc(sizeof(Armario));
auxArmarioTest2->ID = 2;

//Dynamic array of pointer Armario:
pArmario arrArmariosPointers = malloc(sizeof(pArmario) * 5);
//Test
pArmario auxA;
auxA = arrArmariosPointers + 0; //I know, it's useless :)
auxA = auxArmarioTest1;
auxA = arrArmariosPointers + 1;
auxA = auxArmarioTest2;

printf("\nA%d",(arrArmariosPointers+0)->ID);
printf("\nA%d",(arrArmariosPointers+1)->ID);

free(auxArmarioTest1);
free(auxArmarioTest2);

The result I get is:

A0
A0

What I'm doing wrong, again?

UPDATE 2:

Forget my update 1, it was dumb. I'm just changing auxA.

SOLUTION:

pArmario* arrArmariosPointers = malloc(sizeof(pArmario) * 5);

arrArmariosPointers[0] = auxArmarioTest1;
arrArmariosPointers[1] = auxArmarioTest2;

printf("\nA%d",arrArmariosPointers[0]->ID);
printf("\nA%d",arrArmariosPointers[1]->ID);

Thanks everyone.


Solution

  • *(arrArmariosPointers + idCorredor) = auxArmarioTest1;
    

    here arrArmariosPointers + idCorredor is a pArmario or struct recArmario *, dereferencing it give you a struct recArmario which you then assign to auxArmarioTest1 which is a struct recArmario *. In short, you are assigning a pointer to a struct, thus the error

    for your update 1, this may be what you are trying to achieve?

    pArmario * arrArmariosPointers = malloc(sizeof(pArmario) * 5);
    arrArmariosPointers[0] = auxArmarioTest1;
    arrArmariosPointers[1] = auxArmarioTest2;
    
    printf("\nA%d",(arrArmariosPointers[0])->ID);
    printf("\nA%d",(arrArmariosPointers[1])->ID);