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 to use pointer to pointer to access pointer element in struct?

#include<stdlib.h>
typedef struct
{
    int *member;
} mystruct;

void main(int argc, char *argv)
{
    mystruct **data;
    data = (mystruct**)malloc(sizeof(mystruct*));
    int c = 5;
    printf("%x", data);
    (*data)->member = &c;
    printf("Member: %d", *((*data)->member));
}

Error: Segmentation fault

I expected it would print "5" in the source code

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

>Solution :

In this statement

data = (mystruct**)malloc(sizeof(mystruct*));

you allocated memory for one pointer of the type mystruct *. That is uninitialized.

Thus dereferencing this uninitialized pointer obtained by the expression *data

(*data)->member = &c

invokes undefined behavior.

At least you should write

data = (mystruct**)malloc(sizeof(mystruct*));
*data = malloc( sizeof( mystruct ) );

That is you need to allocate memory for an object of the type mystruct the data member member of which will be assigned.

Also pay attention to that using the conversion specifier %x to output a pointer

printf("%x", data);

also invokes undefined behavior. Instead you need to write

printf("%p\n", ( void * )data);

Or you could include header <inttypes.h> and write

#include <inttypes.h>

//...

printf("%" PRIxPTR "\n", ( uintptr_t )data);
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