C structs and Pointers

C Pointers to struct

Here’s how you can create pointers to structs.

  1. struct name {
  2. member1;
  3. member2;
  4. .
  5. .
  6. };
  7. int main()
  8. {
  9. struct name *ptr, Harry;
  10. }

Here, ptr is a pointer to struct.


Example: Access members using Pointer

To access members of a structure using pointers, we use the -> operator.

  1. #include <stdio.h>
  2. struct person
  3. {
  4. int age;
  5. float weight;
  6. };
  7. int main()
  8. {
  9. struct person *personPtr, person1;
  10. personPtr = &person1;
  11. printf("Enter age: ");
  12. scanf("%d", &personPtr->age);
  13. printf("Enter weight: ");
  14. scanf("%f", &personPtr->weight);
  15. printf("Displaying:\n");
  16. printf("Age: %d\n", personPtr->age);
  17. printf("weight: %f", personPtr->weight);
  18. return 0;
  19. }

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

Now, you can access the members of person1 using the personPtr pointer.

By the way,

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

Dynamic memory allocation of structs

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

Sometimes, the number of struct 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 of structs

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. struct person {
  4. int age;
  5. float weight;
  6. char name[30];
  7. };
  8. int main()
  9. {
  10. struct person *ptr;
  11. int i, n;
  12. printf("Enter the number of persons: ");
  13. scanf("%d", &n);
  14. // allocating memory for n numbers of struct person
  15. ptr = (struct person*) malloc(n * sizeof(struct person));
  16. for(i = 0; i < n; ++i)
  17. {
  18. printf("Enter first name and age respectively: ");
  19. // To access members of 1st struct person,
  20. // ptr->name and ptr->age is used
  21. // To access members of 2nd struct person,
  22. // (ptr+1)->name and (ptr+1)->age is used
  23. scanf("%s %d", (ptr+i)->name, &(ptr+i)->age);
  24. }
  25. printf("Displaying Information:\n");
  26. for(i = 0; i < n; ++i)
  27. printf("Name: %s\tAge: %d\n", (ptr+i)->name, (ptr+i)->age);
  28. return 0;
  29. }

When you run the program, the output will be:

Enter the 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 struct variables are created where n is entered by the user.

To allocate the memory for n number of struct person, we used,

  1. ptr = (struct person*) malloc(n * sizeof(struct person));

Then, we used the ptr pointer to access elements of person.

Leave a Reply

Your email address will not be published. Required fields are marked *