c-example-demonstarte-of-STRUCTURE-WITH-POINTER
admin
#c-example-demonstarte-of-STRUCTURE-WITH-POINTER
If you are learning C programming, understanding how to use structures with pointers is essential. In this article, we will explore how to implement structures in C and demonstrate two common methods for accessing structure members using pointers. Let's dive into the details.
A structure in C is a user-defined data type that allows grouping different types of variables under one name. It is useful for creating complex data types that represent real-world entities. For example, a structure can represent a student, employee, or car.
There are two ways to retrieve members of a structure using pointers:
.
) and asterisk (*
) operators:
->
):
Declaring a structure pointer is similar to declaring a structure variable. You can declare both inside or outside the main()
function. To declare a pointer variable in C, use the asterisk (*
) symbol before the variable name.
struct StructureName *pointerName;
Below is a practical example to demonstrate the use of structures with pointers in C:
#include<stdio.h>
struct student {
int sno, m;
char sname[20];
float per;
};
void main() {
struct student s1, *p;
p = &s1; // Assign the address of s1 to the pointer p
printf("\nEnter student number, marks, and name of the student: ");
scanf("%d%d%s", &p->sno, &p->m, p->sname); // Using arrow operator to access members
// Calculate percentage
p->per = p->m / 3.0;
printf("\nStudent Details:\n");
printf("Student Number: %d\nMarks: %d\nName: %s\nPercentage: %.2f%%\n",
p->sno, p->m, p->sname, p->per);
}
Structure Definition:
student
structure is created with the following members:
sno
(student number): int
m
(marks): int
sname
(student name): char[20]
per
(percentage): float
Pointer Initialization:
p
of type struct student
is declared.s1
is assigned to p
using p = &s1;
.Input and Output:
scanf
.->
) is used to access and modify the structure members via the pointer.->
operator is shorthand for (*pointer).member
and is more commonly used.
In this example, we created a student
structure containing various data elements such as sno
(student number), m
(marks), sname
(name), and per
(percentage). The pointer p
was used to access and modify these elements efficiently.
Using pointers with structures is a powerful feature in C programming that helps in efficient memory management and data manipulation. Mastering this concept will enhance your ability to write efficient and robust C programs.