6.1 Example
Using Pointers with Structs in Functions
In C, structs are often passed by reference using pointers to avoid copying large amounts of data. This is especially useful for modifying struct members inside functions.
Example: Passing a Pointer to a Struct to Modify its Members
#include <stdio.h>
typedef struct { int x; int y;} Point;
void move_point(Point *p, int dx, int dy) { p->x += dx; // Modify the x coordinate p->y += dy; // Modify the y coordinate}
int main() { Point p1 = {5, 10};
printf("Before move: (%d, %d)\n", p1.x, p1.y);
// Move the point by 3 units in the x direction and 4 units in the y direction move_point(&p1, 3, 4);
printf("After move: (%d, %d)\n", p1.x, p1.y);
return 0;}
Output:
Before move: (5, 10)After move: (8, 14)