Skip to main content

Structures and Pointers in C

Pointer to Strutures

  • Pointers to structures are used in C to access and manipulate data within a structure.

  • Here are the basic steps for using pointers to structures in C:

Declare the structure type

Define the structure using the struct keyword and specify the members of the structure.

Declare a structure variable

Declare a variable of the structure type using the syntax struct structure_name variable_name;.

Declare a pointer to the structure

Declare a pointer variable of the structure type using the syntax struct structure_name *ptr;.

Initialize the pointer

Set the pointer to point to the address of the structure variable using the address-of operator &, like this: ptr = &variable_name;.

Access the members of the structure using the pointer

Use the arrow operator -> to access the members of the structure using the pointer, like this: ptr->member_name.

Example

#include <stdio.h>

struct student
{
char name[50];
int age;
float gpa;
};

int main()
{
struct student s = {"John Doe", 21, 3.5};
struct student *ptr = &s; // pointer to structure

// Accessing structure members using the pointer
printf("Student name: %s\n", ptr->name);
printf("Student age: %d\n", ptr->age);
printf("Student GPA: %.2f\n", ptr->gpa);

return 0;
}
Output:

Explanation

  • A structure student is defined with members for name, age, and GPA.
  • The program then creates a structure variable s with values for the members, and declares a pointer ptr of type struct student * and initializes it to point to the address of the s variable.
  • Finally, the program uses the pointer to access the members of the structure and print their values to the console.
tip

Note that when accessing members of the structure using a pointer, we use the -> operator instead of the . operator used with a regular structure variable.