C : Program for creating structure and accept structure members using structure pointer
Program:
//c program for creating structure and accept structure members using structure pointer
#include<stdio.h>
struct student
{
int rollno;
char class[20];
};
int main()
{
struct student std;
struct student *ptr = &std;
printf("Enter roll number of student :");
scanf("%d", &ptr->rollno);
printf("Enter class of student :");
scanf("%s", ptr->class);
printf("\nRoll number of student : %d\n", (*ptr).rollno);
printf("class of student :%s", (*ptr).class);
return 0;
}
Output :
Explanation :
This C program demonstrates the use of structures and structure pointers to accept and display student information. Here's an explanation of the program:
1. It starts by including the standard input-output library using `#include <stdio.h>`.
2. A structure named `student` is defined, which contains two members:
- `rollno` of type integer to store the roll number.
- `class` of type character array (string) with a maximum length of 20 characters to store the class name.
3. Inside the `main` function:
- An instance of the `student` structure is declared as `std`.
- A pointer to a `student` structure named `ptr` is created, and it's initialized with the address of the `std` structure.
4. The program prompts the user to enter the roll number of the student using `printf`, and then it reads the input into the `rollno` member of the structure using `scanf` with the `&` operator: `scanf("%d", &ptr->rollno);`.
5. Next, the program prompts the user to enter the class of the student using `printf`, and it reads the input into the `class` member of the structure. Note that in this case, you don't need the `&` operator since `ptr->class` is already an array: `scanf("%s", ptr->class);`.
6. Finally, the program prints the entered information using `printf`. It displays the roll number and class of the student by accessing the structure members through the pointer using the `->` operator: `printf("\nRoll number of student : %d\n", (*ptr).rollno);` and `printf("Class of student: %s", (*ptr).class);`.
7. The program ends by returning 0, indicating successful execution.
This program essentially allows you to create a student structure, accept information for a student, and then display that information using a structure pointer.
(Explanation credit — Chat GPT)