Pointer
to structures
Its Syntax:
struct Employee
{
int empNum;
char
empName [30];
float
salary;
char
dept[15];
};
struct Employee
emp;
empNum empName salary dept
|
|
|
|
1000
1002 1032 1036
Accessing address.
&emp Ã
base address à 1000
&emp.empNum à 1000
emp.empName à 1002 ( char array, itself is an
address )
&emp.salary à 1032
emp.dept à 1036 ( char array, itself is an address )
Program to display the address of
structure elements
#include<stdio.h>
int main()
{
struct employee
{
int empNum;
char empName[30];
float salary;
char dept[15];
};
struct employee emp;
printf("\n
%u", &emp.empNum);
printf("\n
%u",emp.empName);
printf("\n
%u",&emp.salary);
printf("\n
%u",emp.dept);
getch();
}
Declaring pointer to structure:
struct employee
{
int empNum;
char empName[30];
float salary;
char dept[15];
};
struct employee emp;
ptr = &emp;
program for Declaring a pointer:
#include<stdio.h>
int main()
{
struct employee
{
int empNum;
char empName[30];
float salary;
char dept[15];
};
struct employee emp;
struct employee *ptr;
ptr=&emp;
printf("\n %u",&emp);
printf("\n %u", ptr);
getch();
}
Accessing structure members through the
address.
Ã
is an operator to access structure members through the address.
struct employee
{
int empNum;
char empName[30];
float salary;
char dept[15];
};
struct employee emp;
struct employee *ptr;
ptr = &emp;
ptrÃ
empNum;
ptrÃ
empName;
ptrà salary
ptrà dept;
Assigning values:
ptrÃ
empNum=1001;
strcpy(ptrà empName,”mnrao”);
ptrà salary=5000;
strcpy(ptrà dept,”admin”);
#include<stdio.h>
int main()
{
struct employee
{
int empNum;
char empName[30];
float salary;
char dept[15];
};
struct employee
emp={1001,"hello",4500.50,"admin"};
struct employee *ptr;
ptr=&emp;
printf("\n
%d %s %f
%s ",ptr->empNum,ptr->empName,ptr->salary,ptr->dept);
getch();
}
Note: The programs given here are pre compiled and pre runned. If the user want to recompile and run the program again they can use the following compiler given after each and ever program.
0 Comments