Pointers in Structures in C

C language – Pointers in Structures

In C, a pointer is a variable that stores the memory address of another variable. A pointers in structures in C is a user-defined data type that consists of a collection of variables of different data types.

You can use pointers in structures in C to reference the memory location of a structure variable.

Pointers in Structures in C

Pointer in Structures in C

Here is an example of how you might declare a structure and a pointer to it in C:

struct Student {
char name[30];
int age;
float grade;
};

struct Student *ptr;

To access the members of a structure using a pointer, you can use the “arrow” operator (->). For example:

ptr->name;   // accesses the "name" member of the structure pointed to by "ptr"
ptr->age;    // accesses the "age" member of the structure pointed to by "ptr"
ptr->grade;  // accesses the "grade" member of the structure pointed to by "ptr"

You can also use the “dot” operator (.) to access the members of a structure, but this requires that you have the actual structure variable rather than just a pointer to it. For example:

struct Student s;

s.name;   // accesses the "name" member of the structure "s"
s.age;    // accesses the "age" member of the structure "s"
s.grade;  // accesses the "grade" member of the structure "s"

Pointers to structures can be useful when you want to pass a structure to a function by reference (i.e., modify the structure within the function) or when you want to create an array of structures and access the elements using pointers.

Pass a pointer to the structure to the function:

Run

#include <stdio.h>

struct Point {
int x;
int y;
};

void printPoint(struct Point *p) {
printf("(%d, %d)\n", p->x, p->y);
}

int main() {
struct Point p = {1, 2};
printPoint(&p);
return 0;
}

Output

(1, 2)

In this example, the printPoint function takes a pointer to a struct Point as an argument. The -> operator is used to access the members of the structure through the pointer.