Search code examples
cpointersstructure

Structures and Pointers dereferencing question


The pointer MyStruct* ps points to &s. What is the value, if any, after de-referencing only *ps without accessing any struct members of MyStruct?

#include    <stdio.h>

typedef struct {
    char c;
    int x;
    double d;
} MyStruct;

int main(void) {
    MyStruct s = {'a', 132, 456.789};
    MyStruct* ps = &s;
    
    printf("Member c has a value of %c\n",(*ps).c);
    printf("Member x has a value of %d\n", (*ps).x);
    printf("Member d has a value of %f\n", (*ps).d);    

    /* printf("Here i want to print the outcome of\n", *ps); */
}

EDIT: I finally got the solution! And i know what its containing as value. It's the char 'a'. With printf("%c\n", *ps i got the value inside of *ps. I know i get a warning but still i know now what it contains. Also the comments and other answers were really helpful!


Solution

  • The definition

    MyStruct s = {'a', 132, 456.789};
    

    creates a block in memory looking something like

    +---+
    | c |
    +---+
    | x |
    +---+
    | d |
    +---+
    

    Then the definition

    MyStruct* ps = &s;
    

    modifies it to something like this:

    +----+     +---+
    | ps | --> | c |
    +----+     +---+
               | x |
               +---+
               | d |
               +---+
    

    The "value" of ps is the address of the first member of the s structure object.