Search code examples
cstructstructure

Pointer to struct in C, what is the content?


I was wondering if I have a code like this:

struct something{
    int x;
    float y;
};

int main(void)
{
    struct something *p;
    p = malloc(sizeof(struct something));
    p->x = 2;
    p->y = 5.6;
    return 0;
}

what's the content of *p (with *) if called somewhere? Is it the address of the structure or what?


Solution

  • Here's an example of the usage of *p - that is, dereferencing the pointer:

    #include <stdio.h>
    #include <stdlib.h>
    
    struct something {
        int x;
        float y;
    };
    
    int main(void) {
        struct something *p;
    
        p = malloc(sizeof *p);
    
        p->x = 2;
        p->y = 5.6;
    
        struct something s;
        s = *p;                         // dereference p and copy into s
    
        free(p);
    
        // now check s:
        printf("%d, %.1f\n", s.x, s.y); // prints 2, 5.6
    }