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!
CodePudding user response:
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.
CodePudding user response:
*ps
denotes the entire structure. The “value” of *ps
is an aggregate with the values of all its members. The C standard does not provide any way to print it, but you can assign it to another structure of the same type, pass it to a function that accepts an argument of that type, and return it from a function that has a return type of that type. Effectively, *ps
is the same as s
.
CodePudding user response:
one way to think of it is that
MyStruct* ps;
is the same as
MyStruct *ps;
Which says: '*ps' is a 'MyStruct'