Home > database >  Pointer to struct in C, what is the content?
Pointer to struct in C, what is the content?

Time:04-20

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?

CodePudding user response:

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
}

CodePudding user response:

p is a pointer to struct something. *p will dereference that pointer to give the struct itself. But, here is the catch: struct (*p) is a composite data type, you need to use a . operator to get its member.

(*p).x = 2;
(*p).y = 5.6;

This can also be done without using the indirection operator (*) (as you did):

p->x = 2;
p->y = 5.6;
  • Related