Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How is it possible to access property without "->" in c?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading