Structs and Pointers
When you have a pointer to a struct — which is what malloc returns when allocating one — you can't use the dot operator directly, since p.x would need p to be an actual struct, not a pointer to one. The -> operator is shorthand for dereferencing and then accessing a field in one step: p->x means (*p).x.
#include <stdio.h>
#include <stdlib.h>
struct Point {
int x;
int y;
};
int main() {
struct Point *p = malloc(sizeof(struct Point));
p->x = 3;
p->y = 4;
printf("%d %d\n", p->x, p->y);
free(p);
return 0;
}3 4
What the real compiler error looks like
Using . on a struct pointer instead of -> is a genuinely common C mistake, and the compiler catches it immediately. This is genuinely what gcc reports — captured from a real run, not written to look plausible:
#include <stdio.h>
#include <stdlib.h>
struct Point {
int x;
int y;
};
int main() {
struct Point *p = malloc(sizeof(struct Point));
p.x = 3;
printf("%d\n", p.x);
free(p);
return 0;
}main.c: In function ‘main’:
main.c:11:6: error: ‘p’ is a pointer; did you mean to use ‘->’?
11 | p.x = 3;
| ^
| ->
main.c:12:21: error: ‘p’ is a pointer; did you mean to use ‘->’?
12 | printf("%d\n", p.x);
| ^
| ->GCC's diagnostic here is unusually helpful — it names the exact fix. Not every compiler error in this course will be this forgiving.
Next: function pointers — storing a function itself in a variable, and calling it indirectly.
Practice exercise
Define struct Point with fields x and y. Use malloc to create a Point, set x to 3 and y to 4 through the pointer with ->, print both, then free it.