How to Declare a Pointer to a Struct in C?
Last Updated :
05 Feb, 2024
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++
#include <stdio.h>
#include <stdlib.h>
struct Point {
int x;
int y;
};
int main()
{
struct Point* ptr;
ptr = ( struct Point*) malloc ( sizeof ( struct Point));
ptr->x = 10;
ptr->y = 20;
printf ( "Coordinates: (%d, %d)\n" , ptr->x, ptr->y);
free (ptr);
return 0;
}
|
Output
Coordinates: (10, 20)
To know more, refer to the article – Structure Pointer in C
Share your thoughts in the comments
Please Login to comment...