Pointers to Structure in C

Pointers pointing to structures are called structure pointers. They are just the same as the normal pointers for int, char, and other data types.

Syntax

struct structure_name
{
data-type member-1;
data-type member-2;
data-type member-3;
data-type member-4;
};
main( )
{
struct structure_name *ptr
}

 

Program

#include<stdio.h>
int main()
{
struct student
{
char name[20];
int age;
};
struct student S={"Alisha",18};
struct student *p;
p=&S;


printf("Using variable:\n%s %d\n",S.name,S.age);
printf("Using pointers:\n%s %d\n",p->name,p->age);


}

 

Output

Explanation

We have declared a pointer for the structure by writing struct student *p;

p=&S; pointer ‘p’ is storing the address value of ‘S’, i.e., ‘p’ is pointing to ‘S’.

Firstly, we print the name and age of the student using the variable as we had done before.

Secondly, we write the statement

printf(“Using pointers:\n%s %d\n”,p->name,p->age);

In this statement, we use -> access the member of the structure, i.e., name, from its pointer ‘p’.

We use ‘.’ with structures and ‘->’ with pointers.

 

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.