I've been learning c for a while, and let's say I thought I had a good understanding of pointers though this example is bugging me.
Let's say we have an array in which each element points to a structure. If we allocate space for two elements like in the example bellow:
p = (test**)malloc(2*sizeof(test*));
p[0] = (test*)malloc(sizeof(test));
p[1] = (test*)malloc(sizeof(test));
Here's the structure test:
typedef struct {
char *t;
long long p;
} test;
And now when I assign values to the variables like below:
(*p)[1].t = (char*)malloc(10*sizeof(char));
strcpy((*p)[1].t, "test");
(*p)[1].p = 10;
p[1]->t = (char*)malloc(10*sizeof(char));
p[1]->p = 20;
strcpy(p[1]->t, "test34e");
They fill completely different chunks of memory. How am I able to access property t at all in this example (*p)[1].t
?
CodePudding user response:
It seems you mean the following
(*p[1] ).t = (char*)malloc(10*sizeof(char));
strcpy( ( *p[1] ).t, "test");
( *p[1] ).p = 10;
That is p[1]
is a pointer. So you can write for example either p[1]->t
or dereferencing the pointer and getting the pointed object of the structure type ( *p[1] ).t
.