how to use pointer to pointer to access pointer element in struct?

Advertisements
#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

>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);

Leave a ReplyCancel reply