C Programming language

adplus-dvertising
Pointer to Structure
Previous Home Next

In structure we can access multiple data types under a single name for easy m­­anipulation. example we want to refer to address with multiple data like house number, street, zip code, country. C is support structure which allows that we want to wrap one or more variables with different data types. A structure can contain any valid data types like int, char, float even arrays and other structures. Each variable in structure is called a structure member.

Example

struct address{
    unsigned int house_number;
     char street_name[50];
     int zip_code;
     char country[50];
  };

A structure can contain pointers as structure members and we can create a pointer to a structure as follows:

struct invoice
  {
     char* code;
     char date[12];
   };
		
   struct address billing_addr;
   struct address *pa = &billing_addr;

Example of pointer to structure

#include <stdio.h>
	#include <string.h>

struct man{                      /* the structure type */
    char lastname[20];           /* last name */
    char firstname[20];          /* first name */
    int age;                     /* age */
    float rate;                  /* e.g. 12.75 per hour */
};

struct man my_struct;            /* define the structure */
void show_name(struct man *p);   /* function prototype */

int main(void)
{
    struct man *st_ptr;          /* a pointer to a structure */
    st_ptr = &my_struct;         /* point the pointer to my_struct */
    strcpy(my_struct.lastname,"tiger");
    strcpy(my_struct.firstname,"rakesh");
    printf("%s ",my_struct.firstname);
    printf("%s",my_struct.lastname);
    my_struct.age = 30;
    show_name(st_ptr);           /* pass the pointer */
    return 0;
}

void show_name(struct man *p)
{
    printf("%s ", p->firstname);  /* p points to a structure */
    printf("%s ", p->lastname);
    printf("%d", p->age);
};

Output: rakesh tigerrakesh tiger 30

Previous Home Next