Before you learn about how pointers can be used with structs, be sure to check these tutorials:
C Pointers to struct
Here's how you can create pointers to structs.
struct name {
member1;
member2;
.
.
};
int main()
{
struct name *ptr, Harry;
}
Here, ptr is a pointer to struct.
Example: Access members using Pointer
To access members of a structure using pointers, we use the -> operator.
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->ageis equivalent to(*personPtr).agepersonPtr->weightis 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
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,
ptr = (struct person*) malloc(n * sizeof(struct person));
Then, we used the ptr pointer to access elements of person.