Pointers to Structures
In C language, you can use pointers to structures to access and manipulate the members of a structure dynamically, and to pass structures as arguments to functions. Here’s an example:
#include <stdio.h>
#include <stdlib.h>
struct student {
char name[50];
int age;
float gpa;
};
void print_student(struct student *s) {
printf("Name: %s\n", s->name);
printf("Age: %d\n", s->age);
printf("GPA: %.2f\n", s->gpa);
}
int main() {
// Declare a student structure and initialize it
struct student john;
strcpy(john.name, "John Smith");
john.age = 19;
john.gpa = 3.2;
// Declare a pointer to a student structure and assign the address of john to it
struct student *john_ptr = &john;
// Print out the information for john using the print_student function
printf("Information for john:\n");
print_student(john_ptr);
// Dynamically allocate memory for a new student structure and set its values
struct student *jane_ptr = malloc(sizeof(struct student));
strcpy(jane_ptr->name, "Jane Doe");
jane_ptr->age = 20;
jane_ptr->gpa = 3.8;
// Print out the information for jane using the print_student function
printf("Information for jane:\n");
print_student(jane_ptr);
// Free the dynamically allocated memory for jane
free(jane_ptr);
return 0;
}
In this example, we first define a struct
called student
, which contains three members: a character array for the student’s name, an integer for their age, and a floating-point number for their GPA.
We then declare a print_student
function that takes a pointer to a student
structure as its argument and prints out the information for that student using the arrow operator ->
to access the structure members.
In main
, we first declare a student
structure called john
and initialize its values. We then declare a pointer to a student
structure called john_ptr
and assign the address of john
to it using the address-of operator &
.
We call the print_student
function to print out the information for john
using john_ptr
.
We then dynamically allocate memory for a new student
structure called jane_ptr
using the malloc
function. We set the values for jane_ptr
using the arrow operator ->
. We then call print_student
to print out the information for jane_ptr
.
Finally, we free the dynamically allocated memory for jane_ptr
using the free
function.