Open In App

How to Pass Array of Structure to a Function in C?

Last Updated : 19 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

An array of structures in C is a data structure that allows us to store multiple records of different data types in a contiguous memory location where each element of the array is a structure. In this article, we will learn how to pass an array of structures from one function to another in C.

Passing an Array of Struct to Functions in C

We can pass an array of structures to a function in a similar way as we pass an array of any other data type i.e. by passing the array as the pointer to its first element.

Syntax to Pass Array of Struct to Function in C

// using array notation
returnType functionName(struct structName arrayName[], dataType arraySize);

// using pointer notation
returnType functionName(struct structName *arrayName, dataType arraySize) );

Here,

  • functionName is the name of the function.
  • structName is the name of the struct.
  • *arrayName is a pointer to the array of structures.
  • arraySize is the size of an array of structures.

C Program to Pass Array of Struct to Function

The below program demonstrates how we can pass an array of structures to a function in C.

C
// C Program to pass array of structures to a function
#include <stdio.h>

// Defining the struct
struct MyStruct {
    int id;
    char name[20];
};

// Function to print the array of structures
void printStructs(struct MyStruct* array, int size)
{
    for (int i = 0; i < size; i++) {
        printf("Struct at index %d: ID = %d, Name = %s\n",
               i, array[i].id, array[i].name);
    }
}

int main()
{
    // Declaring an array of structs
    struct MyStruct myArray[] = {
        { 1, "P1" },
        { 2, "P2" },
    };

    // Passing the array of structures to the function
    printStructs(myArray, 2);

    return 0;
}

Output
Struct at index 0: ID = 1, Name = P1
Struct at index 1: ID = 2, Name = P2

 

 

 


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads