Reputation: 11
I'm trying to make an array of pointers that points to structures addresses, here's the code:
#include <stdio.h>
#include <stdlib.h>
typedef struct poo {
int a,b;
} poo;
int main() {
struct poo *adres,poo;
poo.a = 2;
I'm wondering why this works :
adres = &poo;
printf("%d\n",adres->a);
and when I try to make an array of pointers it doesn't work :
adres = malloc(4*sizeof(*adres));
adres[0] = &poo;
printf("%d\n",adres[0]->a);
Error :
poo.c: In function ‘main’: poo.c:23:13: error: incompatible types when
assigning to type ‘struct poo’ from type ‘struct poo *’
adres[0] = &poo;
^ poo.c:25:26: error: invalid type argument of ‘->’ (have ‘struct poo’)
printf("%d\n",adres[0]->a);
^
Upvotes: 0
Views: 87
Reputation: 1484
adres = malloc(4*sizeof(*adres));
This is causing problem.
What this means is to allocate 4*sizeof (struct poo)
bytes as tyoe of *adres
is struct poo
and then assign that address to adres
.
Then this line
adres[0] = &poo;
The type of adres[0]
is struct poo
whereas type of &poo
is struct poo*
. So type mismatch!
To store the address of struct variables we need an array of pointers to struct variables. which can be accomplished using dynamic memory allocation or statically depending upon requirement.
Static Memory allocation
struct poo *adresArray[4];
Use this when you know in advance the number of struct
variable pointers to create and also do not want to delete (free
) or add the pointers at runtime.
Dynamic Memory allocation
poo **adresArray = malloc(n *sizeof(adres));
Use this when you do not know in advance the number of struct
variable pointers to create and also you do want to delete (free
) or add the pointers at runtime.
Correct code would be: (Dynamic Memory Allocation)
poo **adresArray = malloc(n *sizeof(adres));
if(!adresArray)
{
printf("Malloc failed!\n");
exit(1);
}
adresArray[0] = &poo;
Upvotes: -1
Reputation: 2566
struct poo *adres
is a pointer to a struct poo
, not a pointer to a pointer to struct poo
, which is what an array of pointers is. If you want an array of pointers (assuming you wanted an array of 4 pointers), it would be:
struct poo **adres;
adres = malloc(4*sizeof(*adres)); /* this allocates space for 4 pointers */
adres[0] = &poo;
Upvotes: 0
Reputation: 409176
Because adres[0]
is not a pointer. If you want to copy the structure poo
then do adres[0] = poo
, it's that simple.
Then since adres[0]
is not a pointer, you need to use the normal structure-access syntax using a dot to access members in the structures, e.g adres[0].a
.
Upvotes: 2