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

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

王林
Release: 2023-08-26 18:45:05
forward
1513 people have browsed it

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;
Copy after login

For example- struct Student *s -

Access

The following explains how to access the structure pointer.

Ptr-> membername;
Copy after login

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

Sample program

The following program shows the usage of structure pointers-

#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 ( );
}
Copy after login

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
Copy after login

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;
}
Copy after login

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
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template