C Structure & Pointers
In this page:
What is a Structure Pointer?
This is the natural counterpart to how a structure variable holds the data directly -- a structure pointer instead holds where that data lives, which is essential once you start allocating structures dynamically with malloc().
Example: What is a Structure Pointer?
#include <stdio.h>
struct Point { int x; };
int main() {
struct Point p = {5};
struct Point *ptr = &p;
printf("%d", ptr->x);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
The Arrow Operator (->)
ptr->name is exactly equivalent to (*ptr).name, but is far more readable -- in practice almost all real-world C code uses the arrow operator rather than the dot-and-parentheses form.
Example: The Arrow Operator (->)
#include <stdio.h>
struct Student { char name[20]; };
int main() {
struct Student s = {"Alice"};
struct Student *ptr = &s;
printf("%s", ptr->name);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Dereferencing with Dot Notation
The parentheses around *ptr are mandatory because the dot operator (.) binds more tightly than the dereference operator (*) -- writing *ptr.member without parentheses would incorrectly try to dereference ptr.member instead.
Example: Dereferencing with Dot Notation
#include <stdio.h>
struct Point { int x; };
int main() {
struct Point p = {5};
struct Point *ptr = &p;
printf("%d", (*ptr).x);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Dynamically Allocating Structures
This is exactly how you build linked lists, trees, and other dynamic data structures in C, since each new node's memory doesn't exist until you explicitly request it at runtime with malloc(sizeof(struct Node)).
Example: Dynamically Allocating Structures
#include <stdio.h>
#include <stdlib.h>
struct Point { int x; };
int main() {
struct Point *p = malloc(sizeof(struct Point));
p->x = 10;
printf("%d", p->x);
free(p);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Pointers inside Structures
A struct Node containing a Node *next member is the fundamental building block of linked lists -- each node stores the address of the next one, letting you chain together an arbitrary number of elements without a fixed array size.
Example: Pointers inside Structures
#include <stdio.h>
struct Node {
int value;
struct Node *next;
};
int main() {
struct Node second = {2, NULL};
struct Node first = {1, &second};
printf("%d %d", first.value, first.next->value);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: