Passing Structure to Function in C


Reading time: 20 minutes | Coding time: 5 minutes

In this article, we will learn how to pass structure as a function parameter in C. Before that, we will review the basics of structure in C.

Structure is a user-defined data-type, which is used to store data of different data types or data of same data type, structures allow us to treat a group of related variables as a single unit rather than separate entities.

Consider the following examples:

  1. To locate a point in a two-dimensional co-ordinate system , we use x and y co-ordinates of that point, with the help of structure we can define our own data type, called point which contains x and y co-ordinates of the point as its members.
    Following is the C implementation of the same.
struct point{
    int x;
    int y;
};

(In the above example , point is a data-type defined by us, likewise int,float,double...are data-types defined by creators of C.)
In this example we have declared a structure consisting of two variables of same data type.

  1. We can also store a structure inside a structure.Consider the example of storing specifications of a mobile,where mobile has different parts and each part has its own specifications, lets assume that our mobile has dual camera and we have to store the resolutions of front and back camera and we also want to store other details like name ,memory,color of the mobile...,it can be implemented in C as,
struct camera{
    int frontCamResolution;
    int backCamResolution;
};

struct mobile{
    char mobileName[10];
    struct camera cam;
    char color[10];
    int memory;
};
Question : Can we declare something like this ?


 struct node{
     int data;
     struct node left;
     struct node right;
 };
 
 
No
Yes
Depends on OS
Maybe

No, we cannot do that,since it leads to never-ending recursion and Compiler does not get an exact idea about the memory it should allocate.


We can use structure pointer to solve the above problem,no matter whatever the type of the variable is,pointer always stores the address and it takes fixed amount of memory , below is the implementation of the same in C.

struct node{
    int data;
    struct node* left;
    struct node* right;
};

Structures are no different ,when it comes to passing them to a function or returning them from a function.We can pass a structure to a function in two ways.
1.Pass by value.
2.Pass by reference.


1.Pass by value :
Pass by value means, the value of the passed arguments are copied and any modifications are done to copy of those variables and not to the passed arguments.


Consider the below example of adding a number to the real part of complex number.

#include<stdio.h>

struct complexNumber{
    int realPart;
    int imaginaryPart;
};

// Here we take a complex number as a argument and increase the value of the real 
//part by the given integer value.

void addToRealPart(struct complexNumber , int );
void printComplex(struct complexNumber );

int main(){
    struct complexNumber cnum = {1,2}; //here cnum is the variable of type complexNumber.
    int addval = 10;
    
    printf(" Inside main \n\n");
    
    printf("Before calling the function addToRealPart\n");
    printComplex(cnum); // prints  1 + 2i
    
    addToRealPart(cnum,addval);
    
    printf("After calling the function addToRealPart\n");
    printComplex(cnum); // Again prints 1 + 2i
    //Since this is pass by value ,the changes are made only on the copy not on the original variable.
    return 0;
}

void printComplex(struct complexNumber num){
	printf("%d + %di \n\n",num.realPart,num.imaginaryPart);
}

void addToRealPart(struct complexNumber num,int val){
	num.realPart += val;
	printf(" Outside main \n");
	printComplex(num);
}

output :

 Inside main

Before calling the function addToRealPart
1 + 2i

 Outside main
11 + 2i

After calling the function addToRealPart
1 + 2i

2.Pass by reference :

In Pass by reference, we pass the address of the variable rather than the variable itself ,here no extra copy of the variable is created . All the modifications are reflected outside the function too.Pass by reference is a better way for sending large files as arguments ,since only addresses are passed and copy of the arguments are not made.

Consider the same example of increasing value of the real part of a complex number by the given value.

#include<stdio.h>

struct complexNumber{
    int realPart;
    int imaginaryPart;
};

// Here we take a complex number as a argument and increase the value of the real 
//part by the given integer value.

//to avoid repeated writing of struct keyword we can take the help of typedef

typedef struct complexNumber complexNumber;

void addToRealPart(complexNumber* , int );
void printComplex(complexNumber* );

int main(){
    complexNumber cnum = {1,2}; //here cnum is the variable of type complexNumber.
    int addval = 10;
    
    printf(" Inside main \n\n");
    
    printf("Before calling the function addToRealPart\n");
    printComplex(&cnum); // prints  1 + 2i
    
    addToRealPart(&cnum,addval);
    
    printf("After calling the function addToRealPart\n");
    printComplex(&cnum); //prints 11 + 2i 
    //Since we have passed the address of the variable instead of variable itself,
    //here copy of varaible is not created but the passed variable itself is modified.
    return 0;
}

void printComplex(complexNumber* cptr){
	printf("%d + %di \n\n",cptr->realPart,cptr->imaginaryPart);
}

//  Here (cptr - > realPart) is equivalent to (*cptr).realPart

void addToRealPart(complexNumber* cptr,int val){
	cptr->realPart += val;
	printf(" Outside main \n");
	printComplex(cptr);
}

output :

 Inside main

Before calling the function addToRealPart
1 + 2i

 Outside main
11 + 2i

After calling the function addToRealPart
11 + 2i

We can also create array of structures and pass them to a function, similar to passing in-built type array to a function.

Consider the below example of printing array of complex numbers.

#include<stdio.h>

struct complexNumber{
    int realPart;
    int imaginaryPart;
};


//to avoid repeated writing of struct key word we can take the help of typedef

typedef struct complexNumber complexNumber;

// this function accepts  the array of structure and fills some value 
 // and returns the address of the array

complexNumber* setter(complexNumber numbers[],int size){
	for(int i = 1; i <= size; i++){
		numbers[i].realPart = i;
		numbers[i].imaginaryPart = 10*i;
	}
	return numbers;
}

//this function accepts pointer to the structure array and prints its contents.

void getter(complexNumber* numbers,int size){
	printf("The contents of the array are : \n\n");
	for(int i = 1;i <= size; i++){
		printf("%d + i %d\n",numbers[i].realPart,numbers[i].imaginaryPart);
	}
}

int main(){
	int size = 5;
	complexNumber numbers[size];
	
	complexNumber* ptr = setter(numbers,size);
	getter(ptr,size);
	
	return 0;
}

output :

The contents of the array are :

1 + i 10
2 + i 20
3 + i 30
4 + i 40
5 + i 50