A pointer is a variable that holds the address of another variable. By the same logic, it can even store the address of the structure.
Please refer to the topics below for a clear understanding before reading further:
- Array in C
- Structure in C
- Introduction to pointer
- Pointer declaration, initialization, and dereferencing
Pointer to structure
#include <stdio.h>
#include <string.h>
struct Student
{
char name[10];
int roll;
};
int main ()
{
struct Student stu;
struct Student *ptr = &stu;
ptr->roll = 8;
strcpy (ptr->name, "techaccess");
printf("\n Name is: %s and roll number is: %d\n", ptr->name, ptr->roll);
return 0;
}
Output:
Name is: techaccess and roll number is: 8
Pointers to the array of structures:
The pointer can point to an array of structures that is where each index of an array is a structure.
Sample Code:
#include <stdio.h>
#include <string.h>
struct Student
{
char name[10];
int roll;
};
int main ()
{
struct Student stud[5];
struct Student *ptr= &stud[0];
int i;
for (i = 0; i <5; i++)
{
(ptr + i)->roll = i;
strcpy ((ptr + i)->name, "tech");
}
for (i = 0; i <5; i++)
printf("\n Name is: %s and roll number is: %d\n", (ptr + i)->name, (ptr + i)->roll);
return 0;
}
Output:
Name is: tech and roll number is: 0
Name is: tech and roll number is: 1
Name is: tech and roll number is: 2
Name is: tech and roll number is: 3
Name is: tech and roll number is: 4

Relevant Posts:
- Structure
- Introduction to pointer
- Pointer declaration, initialization, and dereferencing
- Pointer to array
- String and pointers
- Array of pointers
Categories: C Language
Leave a Reply