C pointer within Structure

Pointer Within Structure in C Programming :

  1. Structure may contain the Pointer variable as member.
  2. Pointers are used to store the address of memory location.
  3. They can be de-referenced by ‘*’ operator.

Example :

struct Sample
{
   int  *ptr;  //Stores address of integer Variable 
   char *name; //Stores address of Character String
}s1;
  1. s1 is structure variable which is used to access the “structure members”.
s1.ptr  = #  
s1.name = "Pritesh"
  1. Here num is any variable but it’s address is stored in the Structure member ptr (Pointer to Integer)
  2. Similarly Starting address of the String “Pritesh” is stored in structure variable name(Pointer to Character array)
  3. Whenever we need to print the content of variable num , we are dereferancing the pointer variable num.
printf("Content of Num : %d ",*s1.ptr);
printf("Name : %s",s1.name);

Live Example : Pointer Within Structure

#include<stdio.h>
struct Student
{
   int  *ptr;  //Stores address of integer Variable 
   char *name; //Stores address of Character String
}s1;
int main() 
{
int roll = 20;
s1.ptr   = &roll;
s1.name  = "Pritesh";
printf("\nRoll Number of Student : %d",*s1.ptr);
printf("\nName of Student        : %s",s1.name);
return(0);
}

Output :

Roll Number of Student : 20
Name of Student        : Pritesh

Some Important Observations :

printf("\nRoll Number of Student : %d",*s1.ptr);

We have stored the address of variable ‘roll’ in a pointer member of structure thus we can access value of pointer member directly using de-reference operator.

printf("\nName of Student        : %s",s1.name);

Similarly we have stored the base address of string to pointer variable ‘name’. In order to de-reference a string we never use de-reference operator.