Horje
How to Declare a Pointer to a Struct in C?

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++

// 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;
}

Output

Coordinates: (10, 20)

To know more, refer to the article – Structure Pointer in C




Reffered: https://www.geeksforgeeks.org


C Language

Related
Length of a String without Using the strlen Function in C Length of a String without Using the strlen Function in C
Build Your Own &#039;cat&#039; Command in C for Linux Build Your Own &#039;cat&#039; Command in C for Linux
Buffer in C Programming Buffer in C Programming
C Exercises - Practice Questions with Solutions for C Programming C Exercises - Practice Questions with Solutions for C Programming
Difference between C++ and Java Difference between C++ and Java

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13