Structers In Function And Pointers In C

Posted on November 18, 2023 by Vishesh Namdev
Python C C++ Javascript Java
C Programming Language

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
// Define a Student structure with name and age
struct Student {
char name [50];
int age ;
;
int main () {
// Declare a structure variable
struct Student student1 ;

// Declare a pointer to a Student structure
struct Student * ptrStudent ;

// Assign values using the structure variable
strcpy ( student1.name , "Alice");
student1.age = 20;

// Assign the address of the structure variable to the pointer
ptrStudent = & student1 ;

// Access and display values using the pointer
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
// Define a Student structure with name and age
struct Student {
char name [50];
int age ;
;
// Function to display information about a student
void displayStudent ( struct Student s) {
printf ("Student Name: %s ", s.name);
printf ("Student Age: %d ", s.age);
}

int main () {
// Declare a structure variable
struct Student student1 ;

// Assign values using the structure variable
strcpy ( student1.name , "Bob");
student1.age = 22;

// Call the function and pass the structure as an argument
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.