Home »
C programming language
Pointer to structure in C
C - Pointer to structure: In this tutorial, we will learn how to declare a pointer to structure, how to access elements of the structure using pointer with an example?
Submitted by IncludeHelp, on June 03, 2018
Prerequisite
Example
In this tutorial, we will use a structure for “student”, structure members will be "name" (string type), "age" (integer type), "roll number" (integer type).
Structure declaration
struct student{
char name[50];
int age;
int rollno;
};
Here,
- struct is the keyword to define a structure.
- student is the name of the structure.
- name is the first structure member to store age with maximum of 50 characters, age is second structure member to store age of the student, and rollno is the third structure member to store rol number of the student.
Pointer to structure declaration
struct student *ptr;
Allocating memory to the pointer to structure
ptr = (struct student*)malloc(sizeof(struct student));
The statement will declare memory for one student’s record at run time. Read more about the dynamic memory allocation in C programming language.
Accessing structure members using pointer
The arrow operator (->) is used to access the members of the structure using pointer to structure. For example, we want to access member name, and ptr is the pointer to structure. The statement to access name will be ptr->name.
C program for pointer to structure
#include <stdio.h>
//structure definition
struct student{
char name[50];
int age;
int rollno;
};
//main function
int main(){
//pointer to structure declaration
struct student *ptr;
//allocating memory at run time
ptr = (struct student*)malloc(sizeof(struct student));
//check memory availability
if( ptr == NULL){
printf("Unable to allocate memory!!!\n");
exit(0);
}
//reading values of the structure
printf("Enter student details...\n");
printf("Name? ");
scanf("%[^\n]", ptr->name); //reads string with spaces
printf("Age? ");
scanf("%d", &ptr->age);
printf("Roll number? ");
scanf("%d", &ptr->rollno);
//printing the details
printf("\nEntered details are...\n");
printf("Name: %s\n", ptr->name);
printf("Age: %d\n", ptr->age);
printf("Roll number: %d\n", ptr->rollno);
//freeing dynamically allocated memory
free(ptr);
return 0;
}
Output
Enter student details...
Name? Amit shukla
Age? 21
Roll number? 100
Entered details are...
Name: Amit shukla
Age: 21
Roll number: 100