Home  >  Article  >  Backend Development  >  In C language, a pointer is a pointer to a structure

In C language, a pointer is a pointer to a structure

王林
王林forward
2023-08-26 18:45:051486browse

In C language, a pointer is a pointer to a structure

The structure pointer saves the addition of the entire structure.

It is used to create complex data structures, such as linked lists, trees, graphs, etc.

Members of a structure can be accessed using a special operator called the arrow operator ( -> ).

Declaration

The following is the declaration of a pointer to a structure in C programming -

struct tagname *ptr;

For example- struct Student *s -

Access

The following explains how to access the structure pointer.

Ptr-> membername;

For example - s->sno, s->sname, s->marks;

Sample program

The following program shows the usage of structure pointers- p>

#include<stdio.h>
struct student{
   int sno;
   char sname[30];
   float marks;
};
main ( ){
   struct student s;
   struct student *st;
   printf("enter sno, sname, marks:");
   scanf ("%d%s%f", & s.sno, s.sname, &s. marks);
   st = &s;
   printf ("details of the student are");
   printf ("Number = %d</p><p>", st ->sno);
   printf ("name = %s</p><p>", st->sname);
   printf ("marks =%f</p><p>", st ->marks);
   getch ( );
}

Output

Let us run the above program, it will produce the following result-

enter sno, sname, marks:1 Lucky 98
details of the student are:
Number = 1
name = Lucky
marks =98.000000

Example 2

Consider another example which explains structure pointers function.

Real-time demonstration

#include<stdio.h>
struct person{
   int age;
   float weight;
};
int main(){
   struct person *personPtr, person1;
   personPtr = &person1;
   printf("Enter age: ");
   scanf("%d", &personPtr->age);
   printf("Enter weight: ");
   scanf("%f", &personPtr->weight);
   printf("Displaying:</p><p>");
   printf("Age: %d</p><p>", personPtr->age);
   printf("weight: %f", personPtr->weight);
   return 0;
}

Output

Let us run the above program, it will produce the following results -

Enter age: 45
Enter weight: 60
Displaying:
Age: 45
weight: 60.000000

The above is the detailed content of In C language, a pointer is a pointer to a structure. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete