Structure Pointers
in C is like an arrow pointing to a labeled box (structure). You use the arrow operator (->) to look inside the box without opening it directly. It lets you access and manipulate the data within the structure using the pointer.
Syntax of Structure
#include
<stdio.h>
Copy Code
struct
Student
{
char
name
[50];
int
age
;
;
int
main
() {
struct
Student
student1
;
struct
Student
*
ptrStudent
;
strcpy
(
student1.name
, "Alice");
student1.age
= 20;
ptrStudent
=
&
student1
;
printf
("Student Name: %s
",
ptrStudent
->
name
);
printf
("Student Age: %d
",
ptrStudent
->
age
);
return
0;
}
In this example:
1. We define a
Student
structure with
name
and
age
members.
2. A structure variable
student1
is declared and values are
assigned
to its members.
3. We declare a pointer
ptrStudent
to a struct Student.
3. The address of
student1
is assigned to the pointer using the
address-of operator &
.
4. We access and display the values of the
structure
members through the pointer using the
arrow (->) operator
.
This example shows how to use a pointer to access and manipulate the members of a structure in C.
Structers in Functions
A struct in a function refers to the use of structures as parameters in a function. It allows you to pass a collection of related data (a struct) to a function, enabling the function to work with and manipulate that data. This helps in organizing and streamlining code, especially when dealing with complex data models.
#include
<stdio.h>
Copy Code
struct
Student
{
char
name
[50];
int
age
;
;
void
displayStudent
(
struct
Student
s) {
printf
("Student Name: %s
", s.name);
printf
("Student Age: %d
", s.age);
}
int
main
() {
struct
Student
student1
;
strcpy
(
student1.name
, "Bob");
student1.age
= 22;
displayStudent
(
student1
);
return
0;
}
In this example:
1.We have a Student structure with name and age members
2. The displayStudent function takes a struct Student as a parameter and prints its information.
3. In the main function, we declare a structure variable student1, assign values to its members, and then call the displayStudent function, passing student1 as an argument.
This demonstrates how structures can be easily passed to functions in C, allowing you to encapsulate related data and work with it efficiently within functions.