pointer to the structure in c
Declaring the pointer variable to the structure data type can be considered as a structure to the pointer.
Pointer-pointer is used to store the address of another variable.
The normal structure variable is accessed using the dot(.) operator, but the pointer variable of the structure is accessed using the arrow(->) operator.
Below are the two examples of the structure with the pointer.
1. A pointer to structure variable pointing to a normal structure variable.
2. A pointer to structure variable pointing to the array of a structure variable.
1. A pointer structure variable pointing to a normal structure variable.
In the below program,
bb is the structure variable of the data type book.
*p is the pointer structure variable.
The base address of bb is stored in *p.
All the operations are performed using the pointer variable of the structure datatype book.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | #include<stdio.h> struct book { char name[20]; int prize; }; int main() { struct book bb, *p; p=&bb; printf("Enter the name of the book and its prize:\n"); scanf("%s %d",p->name,&p->prize); printf("\n name= %s\n prize=%d",p->name,p->prize); return 0; } |
output:
2. A pointer structure variable pointing to the array of structure variables.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include<stdio.h> struct material { char name[10]; long int prize; }; int main() { struct material m[5]; struct material *p=NULL; int i; p=m; /*here we do not need to write &m because the base address of array itself point to the variable location*/ printf("Enter the names of cloth material and thier prizes per meter:\n\n"); for(i=0;i<5;i++) { scanf("%s %ld",p->name,&p->prize); p++; } p=m; printf("\nname prize\n"); for(i=0;i<5;i++) { printf("%s %ld\n",p->name,p->prize); p++; } return 0; } |
The address of m[5] is stored in *p.
Input in structure array is taken using *p.
p=m;
The base address of m is stored in pointer p.
/*here, we do not need to write &m because the base address of the array itself points to the variable location*/
While taking input using pointer variable p, p is incremented as p++ at the end of each cycle of for loop, after incrementation, the value under p which is the base address of m[5] will get incremented from m[0] to m[1] and so on until m[4].
After the completion of the loop, the final value under p is the address of m[4].
As we have to print the whole data again, p should contain the address of m[0].
Hence, p=m; statement is used again.
For the printing process again, the for loop is used, and incrementation is done by p++.
output:
Post a Comment
Post a Comment