C pointer within Structure
Contents
Pointer Within Structure in C Programming :
- Structure may contain the Pointer variable as member.
- Pointers are used to store the address of memory location.
- 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;
- s1 is structure variable which is used to access the “structure members”.
s1.ptr = # s1.name = "Pritesh"
- Here num is any variable but it’s address is stored in the Structure member ptr (Pointer to Integer)
- Similarly Starting address of the String “Pritesh” is stored in structure variable name(Pointer to Character array)
- 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.