How to Use Pointer to Structure in C: Syntax and Examples
In C, you use a
pointer to structure to access structure members indirectly by storing the address of a structure variable. Use the -> operator with the pointer to access members, for example, ptr->member.Syntax
To declare a pointer to a structure, use struct StructName *ptr;. To assign it, use the address of a structure variable: ptr = &variable;. Access members through the pointer using ptr->member, which is shorthand for (*ptr).member.
c
struct Person {
char name[50];
int age;
};
struct Person *ptr; // pointer to structure
struct Person person1;
ptr = &person1; // assign address of person1 to ptr
// Access members
ptr->age = 30;
(*ptr).age = 30; // equivalent to ptr->age = 30;Example
This example shows how to create a structure, declare a pointer to it, assign the address, and access members using the pointer.
c
#include <stdio.h>
struct Person {
char name[50];
int age;
};
int main() {
struct Person person1 = {"Alice", 28};
struct Person *ptr = &person1; // pointer to person1
// Access and print members using pointer
printf("Name: %s\n", ptr->name);
printf("Age: %d\n", ptr->age);
// Modify age using pointer
ptr->age = 29;
printf("Updated Age: %d\n", person1.age);
return 0;
}Output
Name: Alice
Age: 28
Updated Age: 29
Common Pitfalls
- Forgetting to assign the pointer to a valid structure address before use causes undefined behavior.
- Using dot operator (
.) with a pointer instead of arrow operator (->). - Dereferencing a NULL or uninitialized pointer leads to crashes.
c
#include <stdio.h>
struct Point {
int x;
int y;
};
int main() {
struct Point p = {10, 20};
struct Point *ptr = NULL;
// Wrong: Using dot operator on pointer
// ptr.x = 15; // Error: ptr is a pointer, not a struct
// Correct: Use arrow operator
ptr = &p;
ptr->x = 15;
printf("x = %d, y = %d\n", p.x, p.y);
return 0;
}Output
x = 15, y = 20
Quick Reference
Pointer to Structure Cheat Sheet:
| Operation | Syntax |
|---|---|
| Declare pointer | struct Type *ptr; |
| Assign address | ptr = &variable; |
| Access member | ptr->member |
| Equivalent access | (*ptr).member |
Key Takeaways
Use the arrow operator (->) to access structure members through a pointer.
Always assign the pointer to a valid structure address before accessing members.
Dereferencing uninitialized or NULL pointers causes program crashes.
The expression ptr->member is shorthand for (*ptr).member.
Pointers to structures allow efficient access and modification of data without copying.