C Tutorial
The way We can have a pointer pointing to an int, or a pointer pointing to a float similarly we can have a pointer pointing to a struct user defined type. such pointers are called as structure pointers.
In programming, we usally deal with collection of ints, chars and floats rather than isolated entities.
Example an entity book is a collection of things like a title, an author, total pages, date of publication and price etc..
Structure is user defined data type which combines dissimilar data types into an entity.
This c program shows how to use the structure pointers.
Declared ptr structure pointer and gets the address of structure variable 'b1' of structure 'book'.
Prints the structure variable b1 enitire elements using structure variable b1 and also using structure pointer ptr and results shows the same.
#include<stdio.h> struct book { int id; char *title; char *author; float price; }; void main() { struct book b1 = {1, "book1", "author1", 20.5}; struct book *ptr; ptr = &b1; printf("\nbook id\ttitle \t auther \t price \n"); printf("%d\t%s\t%s \t%f\n", b1.id, b1.title, b1.author, b1.price); printf("%d\t%s\t%s \t%f\n", ptr->id, ptr->title, ptr->author, ptr->price); }
Output:
$ cc structure.c $ ./a.out book id title auther price 1 book1 author1 20.500000 1 book1 author1 20.500000
We will update one of the element 'title' of the structure variable 'b1' using structure pointer 'ptr' and will check the results again shows same or different. Obiously will be the same result.
#include<stdio.h> struct book { int id; char *title; char *author; float price; }; void main() { struct book b1 = {1, "book1", "author1", 20.5}; struct book *ptr; ptr = &b1; ptr->title = "book2"; printf("\nbook id\ttitle \t auther \t price \n"); printf("%d\t%s\t%s \t%f\n", b1.id, b1.title, b1.author, b1.price); printf("%d\t%s\t%s \t%f\n", ptr->id, ptr->title, ptr->author, ptr->price); }
Output:
$ cc structure.c $ ./a.out book id title auther price 1 book2 author1 20.500000 1 book2 author1 20.500000
C Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page