Structure (or structs) in the C programming language provides a way to combine variables of several data types under one name and pointers provide a means of storing memory addresses. In this article, we will learn how to declare such a pointer to a struct in C.
Declaration of Pointer to Struct in C
To declare a pointer to a struct we can use the struct keyword. First, define a structure then declare a pointer to that structure using the below syntax and that pointer can be used to allocate and access memory for the structure.
Syntax of Declaring Pointer to Struct
struct StructName *ptr ;
or
struct {
// struct members
} *ptr ;
C Program to Declare Pointer to Struct
The below example demonstrates declaration of pointer to a structure.
// C Program to show how to declare and use pointer to // structure #include <stdio.h> #include <stdlib.h> // Define a struct named Point with x and y coordinates struct Point {
int x;
int y;
}; int main()
{ // Declare a pointer to a Point struct
struct Point* ptr;
// Allocate memory for a Point struct using malloc
ptr = ( struct Point*) malloc ( sizeof ( struct Point));
// Assign values to the x and y coordinates
ptr->x = 10;
ptr->y = 20;
// Print the coordinates
printf ( "Coordinates: (%d, %d)\n" , ptr->x, ptr->y);
// Free the allocated memory
free (ptr);
return 0;
} |
Coordinates: (10, 20)
To know more, refer to the article – Structure Pointer in C