Home > Enterprise >  How to access the content of a void pointer inside a struct pointer?
How to access the content of a void pointer inside a struct pointer?

Time:01-07

I have a struct pointer, that points to a struct that has a void pointer as it member, and I need to access the value of this member.

This is the struct with the void pointer I need access

typedef struct {
    void *content;
} st_data;

This is the function to create the struct, it returns a pointer to the struct

st_data *create_struct(void *content)
{
    st_data *new;
    new = malloc(sizeof(st_data));
    new->content = content;
    return new;
}

I cant find the right syntax to print the value of the void pointer.

int main()
{
    int *number;
    *number = 10;
    st_data *new_struct = create_struct(number);
    
// just want to print the value of the void pointer 
    printf("%d\n", *(int *)new_struct->content);
    return 0;
}

CodePudding user response:

@pmacfarlane's comment is more important (IMHO), but this will print the value of the pointer (as opposed to what it points to, as your code does):

printf("%p\n", new_struct->content);

CodePudding user response:

You declare a pointer to an int, but it doesn't point to anything:

int *number; // Doesn't point to anything

You then de-reference this pointer, which leads to undefined behaviour:

*number = 10; // BUG - undefined behaviour

You need to actually define a variable to store your number 10, and pass the address of that to your 'constructor':

int number = 10;
st_data *new_struct = create_struct(&number);

Note that while this will work in your simple example, if your 'new_struct' structure outlived this function you'd have a problem, since the 'content' pointer points to something allocated on the stack, which would disappear if the function exited.

  • Related