C Programming Structure and Pointer

In this article, you'll find relevant examples that will help you to work with pointers to access data within a structure.

Structures can be accessed using pointers. Here's how:

struct name {
    member1;
    member2;
    .
    .
};

int main()
{
    struct name *ptr, Harry;
}

Here, a pointer ptr of type struct name is created. The pointer can access members of Harry.


Example: Access structure members using pointer

#include <stdio.h>
struct person
{
   int age;
   float weight;
};

int main()
{
    struct person *personPtr, person1;
    personPtr = &person1;   

    printf("Enter age:");
    scanf("%d", &personPtr->age);

    printf("Enter weight:");
    scanf("%f", &personPtr->weight);

    printf("Displaying:\n");
    printf("Age: %d\n", personPtr->age);
    printf("weight: %f", personPtr->weight);

    return 0;
}

In this example, the address of person1 is stored in personPtr pointer variable using code personPtr = &person1;.

Now, you can access members of person1 using personPtr pointer. For that we use -> operator.

By the way,

  • personPtr->age is equivalent to (*personPtr).age
  • personPtr->weight is equivalent to (*personPtr).weight

Dynamic memory allocation of structures

Before you proceed this section, we recommend you to check C dynamic memory allocation.

Sometimes, the number of structure variables you declared may be insufficient. You may need to allocate memory during run-time. Here's how you can achieve this in C programming:


Example: Dynamic memory allocation

#include <stdio.h>
#include <stdlib.h>
struct person {
   int age;
   float weight;
   char name[30];
};

int main()
{
   struct person *ptr;
   int i, n;

   printf("Enter number of persons: ");
   scanf("%d", &n);

   ptr = (struct person*) malloc(num * sizeof(struct person));

   for(i = 0; i < n; ++i)
   {
       printf("Enter first name and age respectively: ");
       scanf("%s%d", &(ptr+i)->name, &(ptr+i)->age);
   }

   printf("Displaying Information:\n");
   for(i = 0; i < n; ++i)
       printf("Name: %s\tAge: %d\n", (ptr+i)->name, (ptr+i)->age);

   return 0;
}

When you run the program, the output will be:

Enter number of persons:  2
Enter first name and age respectively:  Harry 24
Enter first name and age respectively:  Gary 32
Displaying Information:
Name: Harry	Age: 24
Name: Gary	Age: 32

In the above example, n number of structure variables are created where n is entered by the user.