C Language: Pointers 22

Pointers And Structures

Normal structure variable

The data elements of the structure / structure variable are accessed using . (dot operator)

Example:
struct student
{
int roll;
char name[20];
float per;
};
struct student s;

scanf(“%d”,&s.roll);
scanf(“%s”,s.name);
scanf(“%f”,&s.per);

Normal Structure Variable

C program to declare a structure named “student” with attibutes roll,name and per. Take input for the details and display them.

#include<stdio.h>
struct student
{
	int roll;
	char name[20];
	float per;
};
int main()
{
	/* Normal Structure variable */
	struct student s;
	printf("Enter roll no ");
	scanf("%d",&s.roll);
	printf("Enter name  ");
	fflush(stdin);
	gets(s.name);
	printf("Enter per ");
	scanf("%f",&s.per);
	
	printf("roll %d  name %s  per %.2f\n",s.roll,s.name,s.per);
	
	return(0);
}
/* Output */
Enter roll no 1001
Enter name  Amit
Enter per 89.69
roll 1001  name Amit  per 89.69

Pointer type structure variable

When pointer type structure variable is declared then in order to access the data elements we use arrow operator.

Example:
struct student
{
int roll;
char name[20];
float per;
};
struct student *s;

scanf(“%d”,&s->roll);
scanf(“%s”,s->name);
scanf(“%f”,&s->per);

Pointer Type Structure Variable

C program to declare a structure named “student” with attibutes roll,name and per. Take input for the details and display them.

#include<stdio.h>
struct student
{
	int roll;
	char name[20];
	float per;
};
int main()
{
	/* Pointer type Structure variable */
	struct student *p,p1;
	p=&p1;
	printf("Enter roll no ");
	scanf("%d",&p->roll);
	printf("Enter name  ");
	fflush(stdin);
	gets(p->name);
	printf("Enter per ");
	scanf("%f",&p->per);
	
	printf("roll %d  name %s  per %.2f\n",p->roll,p->name,p->per);
	
	return(0);
}
/* Output */
Enter roll no 1002
Enter name  Sumit
Enter per 98.99
roll 1002  name Sumit  per 98.99