Structs and pointers
- C course
- Intermediate
- Lesson 30/116
- 5 min
Learn struct pointers and the -> operator.
Structs and pointers
Holding a pointer to a struct is the basic way to pass large data without copying. First you define struct Person { char name[32]; int age; }. Then you create a variable with struct Person p1; and a pointer with struct Person *ptr = &p1;.
To access a field through the pointer you use the arrow operator ->: ptr->age = 30;. This is shorthand for (*ptr).age. Parentheses are required; *ptr.age is parsed wrong. The arrow is both shorter and clearer about intent; that's why it's common in C code.
-> and (*ptr).field are equivalent
The arrow operator -> is essentially the combination of * indirection and . access. That is, ptr->age and (*ptr).age are the same.
Example: you define struct Person p1 = {"Ayşe", 25}; and struct Person *ptr = &p1;. Both ptr->age and (*ptr).age give 25. Without parentheses *ptr.age parses as *(ptr.age); this is a compile error or undefined behavior. Modern C prefers the arrow; it's more readable.
Practice Assign a field via pointer and print
Define struct Person with char name[32]; and int age;. In main, write struct Person p1; and struct Person *ptr = &p1;. Assign with ptr->age = 30; and print with printf("%d\n", ptr->age);.
Starter code
#include <stdio.h>
// Define struct Person (name[32] and age)
// Declare p1 and the ptr pointer
// Set age to 30 via ptr and print
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
struct Person {
char name[32];
int age;
};
int main(void) {
struct Person p1;
struct Person *ptr = &p1;
ptr->age = 30;
printf("%d\n", ptr->age);
return 0;
}Expected output
30
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How do you access age through the ptr pointer?
- &ptr.age
- ptr.age
- *ptr.age
- ptr->age Correct answer
Explanation: The -> operator accesses a field through a pointer.
2 Assign a field through a pointer
struct Person p1;
struct Person *ptr = &p1;
ptr____ = 30;
printf("%d\n", ptr->age);
struct Person p1;
struct Person *ptr = &p1;
ptr->age = 30;
printf("%d\n", ptr->age);
Explanation: ->age accesses age through the ptr pointer.
3 Match the access forms
| Term | Meaning |
|---|---|
ptr->age |
Pointer access |
(*ptr).age |
Indirect access |
p1.age |
Value access |
&p1 |
Address-of |