Structures and Pointers
You can use pointers with structs to make your code more efficient, especially when passing structs to functions or changing their values.
To use a pointer to a struct, just add the * symbol, like you would with other data types.
To access its members, you must use the -> operator instead of the dot . syntax:
Example
// Define a struct
struct Car {
char brand[30];
int year;
};
int main() {
struct Car car = {"Toyota", 2020};
// Declare a pointer to the struct
struct Car *ptr = &car;
// Access members using the -> operator
printf("Brand: %s\n", ptr->brand);
printf("Year: %d\n", ptr->year);
return 0;
}
Passing Struct Pointers to Functions
Here's how you can pass a struct pointer to a function and change its values:
Example
struct Car {
char brand[30];
int year;
};
// Function that takes a pointer to a Car struct and updates the year
void updateYear(struct Car *c) {
c->year = 2025; // Change the year
}
int main() {
struct Car myCar = {"Toyota", 2020};
updateYear(&myCar); // Pass a pointer so the function can change the year
printf("Brand: %s\n", myCar.brand);
printf("Year: %d\n", myCar.year);
return 0;
}
Why Use Struct Pointers?
Using pointers with structs is helpful when:
- You want to avoid copying large amounts of data.
Instead of copying a whole struct, you can just pass a pointer. This makes your program faster and uses less memory.
- You want to change values inside a function.
If you pass a pointer to a struct into a function, the function can change the original values.
- You want to create structs dynamically using memory allocation.
With pointers, you can use malloc() to create structs while the program is running. You will learn more about memory management in a later chapter.
Tip: If you're working with big programs or many values, struct pointers can help make your code cleaner and more efficient.