Pointer to structure

A pointer is a variable that holds the address of another variable. By the same logic, it can even store the address of the structure.

Please refer to the topics below for a clear understanding before reading further:

Pointer to structure

#include <stdio.h>
#include <string.h>

struct Student
{
    char name[10];
    int roll;
};
int main ()
{
  struct Student stu;
  struct Student *ptr = &stu;
  ptr->roll = 8;
  strcpy (ptr->name, "techaccess");
  printf("\n Name is: %s and roll number is: %d\n", ptr->name, ptr->roll);
  
  return 0;
}

Output:

Name is: techaccess and roll number is: 8

Pointers to the array of structures:

The pointer can point to an array of structures that is where each index of an array is a structure.

Sample Code:

#include <stdio.h>
#include <string.h>

struct Student
{
    char name[10];
    int roll;
};

int main ()
{
  struct Student stud[5];
  struct Student *ptr= &stud[0];
  int i;
  for (i = 0; i <5; i++)
  {
     (ptr + i)->roll = i;
     strcpy ((ptr + i)->name, "tech");
  }
  
  for (i = 0; i <5; i++)
  printf("\n Name is: %s and roll number is: %d\n", (ptr + i)->name, (ptr + i)->roll);
 
  return 0;
}

Output:

Name is: tech and roll number is: 0

Name is: tech and roll number is: 1

Name is: tech and roll number is: 2

Name is: tech and roll number is: 3

Name is: tech and roll number is: 4

Relevant Posts:



Categories: C Language

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: