How to Declare and Initialize an Array of Pointers to a Structure in C?
Last Updated :
28 Nov, 2022
Prerequisite:
In C language, arrays are made to store similar types of data in contiguous memory locations. We can make arrays of either primitive data types, like int, char, or float, or user-defined data types like Structures and Unions. We can also make arrays of pointers in C language. Today we will learn how to create arrays of Structure Pointers or pointers-to-structure in C language, both Statically and Dynamically.
Creating structure pointer arrays(Static Arrays)
i). 1D Arrays
We can statically allocate memory for 1D and 2D arrays in C language. The static memory is allocated in the stack memory. We can do static memory allocation of structure pointers in the following ways:
Step 1 - Declaring and initializing 1D arrays
Let's say we have a structure "node", and we created different pointers to this structure. Now, to make a 1D array of those pointers in static memory, we must follow the following syntax:
Syntax:
<struct_name> * <array_name> [ <size_of_array> ] ; // Declaration
<array_name> [ <index_number> ] = <pointer_to_the_structure> ; // Initialization
We can access the pointers inside our array just like we access normal array elements. There is just a little bit of modification that we need to use the arrow operator to access the data present inside our structure pointer.
Step 2 - Accessing the pointers within the array
Syntax:
<array_name> [<index_number>] -> <data to be accessed which is present inside the structure >
Example:
C
// C Program to implement
// structure pointer arrays
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int number;
char character;
} node;
int main(void)
{
// First pointer to structure
node* structure_ptr1 = (node*)malloc(sizeof(node));
// Second pointer to structure
node* structure_ptr2 = (node*)malloc(sizeof(node));
// Declaration of
// structure-pointer-array of size 2
node* struct_array[2];
// Initializing structure pointers
structure_ptr1->number = 100;
structure_ptr1->character = 'a';
structure_ptr2->number = 200;
structure_ptr2->character = 'b';
// Initializing this array with pointers
struct_array[0] = structure_ptr1;
struct_array[1] = structure_ptr2;
// Printing data of structures
printf("Data:\n");
printf("%d and %c\n", struct_array[0]->number,
struct_array[0]->character);
printf("%d and %c\n", struct_array[1]->number,
struct_array[1]->character);
return 0;
}
OutputData:
100 and a
200 and b
In the above example, we have a structure called a "node". We made 2 pointers to that structure namely- 'structure_ptr1' and 'structure_ptr2' and initialized them. After this, we declared an array - "struct_array" of size 2 and initialized it with our struct pointers.
ii). 2D Arrays
Step 1 - Declaring and initializing 2D arrays
Syntax:
<structure_name> * <array_name> [number_of_rows][number_of_columns];
<array_name> [row_number][column_number] = <pointer_to_structure> ;
Step 2- Accessing elements of our 2D array
Syntax:
< array_name >[ <row_number> ][ <column_number> ] -> <data to be accessed which is present inside the structure >;
Example:
C
// C Program to implement
// structure pointer 2-D array
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int number;
char character;
} node;
int main(void)
{
// First pointer to structure
node* structure_ptr1 = (node*)malloc(sizeof(node));
// Second pointer to structure
node* structure_ptr2 = (node*)malloc(sizeof(node));
// Third pointer to structure
node* structure_ptr3 = (node*)malloc(sizeof(node));
// Fourth pointer to structure
node* structure_ptr4 = (node*)malloc(sizeof(node));
// Declaration of
// structure-pointer-array
// of size 2 X 2
node* structure_array[2][2];
// Initializing structure pointers
structure_ptr1->number = 100;
structure_ptr1->character = 'a';
structure_ptr2->number = 200;
structure_ptr2->character = 'b';
structure_ptr3->number = 300;
structure_ptr3->character = 'c';
structure_ptr4->number = 400;
structure_ptr4->character = 'd';
// Initializing this array with pointers
structure_array[0][0] = structure_ptr1;
structure_array[0][1] = structure_ptr2;
structure_array[1][0] = structure_ptr3;
structure_array[1][1] = structure_ptr4;
// Accessing the values of these structure pointers from
// 2D array
printf("Data:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%c - ",
structure_array[i][j]->character);
printf("%d\t\t", structure_array[i][j]->number);
}
printf("\n");
}
}
OutputData:
a - 100 b - 200
c - 300 d - 400
So this is how we declare and initialize a 2D array of structure pointers. Here, we use the same structure - "node" and made 4 pointers for it which were - "structure_ptr1", "structure_ptr2", "structure_ptr3" and "structure_ptr4". After that, we declared a 2D array of size - 2 X 2 namely - structure_array.
Note: The data type of the array must be the same as that of the structure followed by * (asterisk) sign, which signifies array of structure pointers.
Creating structure pointer arrays (Dynamic Arrays)
i). 1D Arrays
As we know that in C language, we can also dynamically allocate memory for our variables or arrays. The dynamically allocated variables or arrays are stored in Heap. To dynamically allocate memory for structure pointer arrays, one must follow the following syntax:
Syntax:
< structure_name > ** < array_name > = <structure_name **> malloc ( sizeof( <structure_name> )* size ) ;
Notice the double-pointer after the structure name and during typecasting malloc to the structure. This double pointer is necessary because we are pointing to an array of structure pointers, and we know that we use double pointers if we want to point to another pointer.
Example:
C
// C Program to implement
// Dynamic Array of structure
// pointer
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int number;
char character;
} node;
int main(void)
{
// First pointer to structure
node* structure_ptr1 = (node*)malloc(sizeof(node));
// Second pointer to structure
node* structure_ptr2 = (node*)malloc(sizeof(node));
// Third pointer to structure
node* structure_ptr3 = (node*)malloc(sizeof(node));
// Fourth pointer to structure
node* structure_ptr4 = (node*)malloc(sizeof(node));
// Initializing structure pointers
structure_ptr1->number = 100;
structure_ptr1->character = 'a';
structure_ptr2->number = 200;
structure_ptr2->character = 'b';
structure_ptr3->number = 300;
structure_ptr3->character = 'c';
structure_ptr4->number = 400;
structure_ptr4->character = 'd';
// Declaring the array dynamically for structure
// pointers
// Note that double pointer is
// used for pointer to pointer
node** structure_array
= (node**)malloc(sizeof(node) * 4);
// Initializing the array of structure pointers
structure_array[0] = structure_ptr1;
structure_array[1] = structure_ptr2;
structure_array[2] = structure_ptr3;
structure_array[3] = structure_ptr4;
// Accessing dynamic 1D arrays - just like static 1D
// arrays
printf("Data:\n");
for (int i = 0; i < 4; i++) {
printf("%c - ", structure_array[i]->character);
printf("%d\t\t", structure_array[i]->number);
printf("\n");
}
}
OutputData:
a - 100
b - 200
c - 300
d - 400
You can clearly see in the above code how we have initialized the structure pointer array at the end. The difference between this and static arrays is just that static arrays are allocated in stack memory, while these are allocated in heap memory. And so, you can resize these arrays anytime you want.
We can access these arrays just like we did with the static ones so there is no change in syntax for that.
Note: In case of static arrays, you can initialize the array all at once during the time of initialization like - node *struct_arr [10 ] = { struct_ptr1, struct_ptr2, struct_ptr3 ..... }, whereas dynamically allocated arrays need to be initialized index-by-index.
ii). 2D Arrays
To allocate dynamic 2D arrays of pointers, first, we will create a 1D array dynamically and then will create sub-arrays at each index of that 1D array (basically an array of arrays containing pointers). Now, this requires the use of triple-pointers. We will understand this with the help of a diagram:
Explanation of the above figure:
- *** st_arr is a triple pointer used to access the 2D array of structure pointers. Now, it is made a triple pointer because we are accessing those arrays, whose each element has a pointer to another array (subarray). And each element of those sub-arrays, have a pointer to the structure.
- Each index of st_arr[i] contains sub-arrays.
- Each index of sub-arrays - st_arr[i][j] contains a pointer to the structure.
- st_ptr is a pointer to the structure.
Example:
C
// C Program to implement
// 2D arrays of structure
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int number;
char character;
} node;
int main(void)
{
// First pointer to structure
node* st_ptr1 = (node*)malloc(sizeof(node));
// Second pointer to structure
node* st_ptr2 = (node*)malloc(sizeof(node));
// Third pointer to structure
node* st_ptr3 = (node*)malloc(sizeof(node));
// Fourth pointer to structure
node* st_ptr4 = (node*)malloc(sizeof(node));
// Initializing structure pointers
st_ptr1->number = 100;
st_ptr1->character = 'a';
st_ptr2->number = 200;
st_ptr2->character = 'b';
st_ptr3->number = 300;
st_ptr3->character = 'c';
st_ptr4->number = 400;
st_ptr4->character = 'd';
// Declaring the array dynamically for structure
// pointers Step - 1
// Note that double pointer is
// used for pointer to pointer
node*** structure_array
= (node***)malloc(sizeof(node***) * 2);
// Used double pointers, at each index to point to
// arrays of structure pointers - Step 2
for (int i = 0; i < 2; i++) {
structure_array[i] = (node**)malloc(sizeof(node**));
}
// Initializing the array of structure pointers - Step
// 3
structure_array[0][0] = st_ptr1;
structure_array[0][1] = st_ptr2;
structure_array[1][0] = st_ptr3;
structure_array[1][1] = st_ptr4;
// Printing the values of these structure pointers from
// array
printf("Data:\n");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%c - ",
structure_array[i][j]->character);
printf("%d\t\t", structure_array[i][j]->number);
}
printf("\n");
}
}
Outputa - 100 b - 200
c - 300 d - 400
- In the above code, as we have already discussed that triple pointer was used to point to an array of arrays containing structure pointers.
- In the second step, we used double pointers as we had to use a pointer, which could point to an array of structure pointers.
- In the third step, we initialized our dynamic 2D array, just like the static 2D array, index by -index.
Similar Reads
C Programming Language Tutorial C is a general-purpose mid-level programming language developed by Dennis M. Ritchie at Bell Laboratories in 1972. It was initially used for the development of UNIX operating system, but it later became popular for a wide range of applications. Today, C remains one of the top three most widely used
5 min read
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() In C, a variable defined in a function is stored in the stack memory. The requirement of this memory is that it needs to know the size of the data to memory at compile time (before the program runs). Also, once defined, we can neither change the size nor completely delete the memory.To resolve this,
9 min read
Decorators in Python In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read