C Programming Structure and Pointer
C Programming Structure and Pointer
www.programiz.com/c-programming/c-structures-pointers
Structures can be created and accessed using pointers. A pointer variable of a structure can be created as below:
struct name {
member1;
member2;
.
.
};
int main()
{
struct name *ptr;
}
#include <stdio.h>
typedef struct person
{
int age;
float weight;
};
int main()
{
struct person *personPtr, person1;
personPtr = &person1; // Referencing pointer to memory address of person1
printf("Displaying: ");
printf("%d%f",(*personPtr).age,(*personPtr).weight);
return 0;
}
In this example, the pointer variable of type struct person is referenced to the address of person1. Then, only
the structure member through pointer can can accessed.
1/2
2. Accessing structure member through pointer using dynamic memory
allocation
To access structure member using pointers, memory can be allocated dynamically usingmalloc() function defined
under "stdlib.h" header file.
#include <stdio.h>
#include <stdlib.h>
struct person {
int age;
float weight;
char name[30];
};
int main()
{
struct person *ptr;
int i, num;
printf("Displaying Infromation:\n");
for(i = 0; i < num; ++i)
printf("%s\t%d\t%.2f\n", (ptr+i)->name, (ptr+i)->age, (ptr+i)->weight);
return 0;
}
Output
2/2