Topics

6/recent/ticker-posts

Pointer to Structures(Pointers Part 4)


 

                  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);

            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;

 struct employee  *ptr;

 

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”);

 

Program to access structure members:


#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.

Post a Comment

0 Comments