C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C programming language

Declaration, Use of Structure Pointers in C programming language.






In this tutorial we are going to learn how a structure pointer is declared and how we can use (access and modify the value of structure members) structure pointer?

Declaration of structure pointer

Just like another pointer variable declaration, a structure pointer can also be declared by preceding asterisk (*) character.

The syntax is:

struct structure_name *strcuture_pointer_variable;

Here,

  • struct is the keyword which tells to the compiler that we are going to declare a structure or structure variable (in some cases struct is not required before structure variable declaration).
  • structure_name is the name of structure that should be declared before structure variable declaration.
  • strcuture_pointer_variable is the name of structure pointer variable, that will be used to access or modify the structure members.

Initialization of structure pointer

As usual, structure pointer should also be initialized by the address of normal structure variable.

Here is the syntax:

strcuture_pointer_variable=&structure_variable;

Access a structure member using structure pointer variable name

To access the members of structure, arrow operator -> is used.

Here is the syntax:

strcuture_pointer_variable->member_name;

Consider the following program

#include <stdio.h>

//structure declaration
struct person{
	char name[30];
	int age;
};

int main(){
	//structure pointer declaration
	struct person per;
	struct person *ptrP;
	
	ptrP=&per; //initialization
		
	printf("Enter name: ");
	scanf("%s",ptrP->name);
	printf("Enter age: ");
	scanf("%d",&ptrP->age);
	
	printf("Name: %s, age: %d\n",ptrP->name,ptrP->age);
	
	return 0;
}

Output

Enter name: Mike
Enter age: 21 
Name: Mike, age: 21

In this example,

  • person is the structure name, which has two members name and age.
  • per is the structure variable name.
  • ptrP is the structure pointer of structure variable per.
  • To access name and age using structure pointer ptrP, we are using ptrP->name and ptrP->age.

COMMENTS