Search code examples
cpointersstructdouble-pointer

How to set value of struct indirectly in c?


I would like to know, how to access first member of struct through pointer. I have tried this:

#include <stdio.h>
#include <stdlib.h>

struct foo
{
    int a;
    char *str;
};

int main()
{
    struct foo *p = malloc(sizeof(struct foo));
    int val = 10;
    *(int**)p = &val; //set the value of the first member of struct foo
    printf("%i\n",p->a);
}

but that print some garbage. How can I set it in similar manner?


Solution

  • The assignment should be:

    *(int*)p = val;
    

    You want to assign to an int member, so the pointer has to be a pointer to int, not pointer to pointer to int. And the value being assigned must be int; &val is a pointer to int.