C Passing Arrays in Functions

In C, passing array in functions is similar to passing variables, however when arrays are passed in functions, they decay into pointers. Also, arrays are contiguous memory locations, therefore, just passing the address of the first element is enough. Arrays can be passed by either declaring formal parameters as sized array, or an unsized array.

Pass 1D Array

Code

#include<stdio.h>

void getArray(int *ptr)
{
	// getting location of first value using ptr
	
	printf("First Value\n");	
	printf("Arr[0] = %d\n",*ptr);
	//incrementing pointer
	ptr++;
	printf("Second Value\n");	
	printf("Arr[1] = %d\n",*ptr);
}

void setArray(int arr[])
{	
	// setting first value to 10
	arr[0] = 10;
}

void printArray(int arr[],int n)
{
	int i;
	for(i=0;i<n;i++)
	{
		printf("%d ",arr[i]);
	}
	printf("\n");
}

int main(void)
{
	
	int arr[] = {1,2,3,4,5};	
	int n;
	
	getArray(arr);
	
	// getting size of array
	n = sizeof(arr)/sizeof(arr[0]);
	printf("Array Before\n");
	// passing array with size
	printArray(arr,n);
	setArray(arr);
	printf("Array After\n");
	printArray(arr,n);
	
	return 0;
	
}

Output

First Value
Arr[0] = 1
Second Value
Arr[1] = 2
Array Before
1 2 3 4 5
Array After
10 2 3 4 5

Pass 2D Array

To pass 2d arrays, you can either provide size of both dimentions or leave the first dimention as blank.

Code

#include<stdio.h>

void getArray(int arr[][2])	// the first dimension can be left empty
{
	int i,j;
	for(i=0;i<2;i++)
	{
		for(j=0;j<2;j++)
			printf("%d ",arr[i][j]);
		printf("\n");
	}
}

int main(void)
{
	// 2d arrays
	int arr[2][2] = {{1,2},{3,4}};	

	getArray(arr);
	return 0;
	
}

Output

1 2
3 4

Trending

C Programming

Remember to follow community guidelines and don't go off topic.