Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
1 views12 pages

Pass Array As Parameter To Functions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views12 pages

Pass Array As Parameter To Functions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Pass Array to Functions in C

Passing an array to a function allows the function to directly access and


modify the original array. In this article, we will learn how to pass arrays to
functions in C.
In C, arrays are always passed to function as pointers. They cannot be
passed by value because of the array decay due to which, whenever array is
passed to a function, it decays into a pointer to its first element. However,
there can be different syntax of passing the arrays as pointers.
The easiest way to pass array to a function is by defining the parameter as
the undefined sized array. Let's take a look at an example:
#include <stdio.h>

// Array passed as an array without the size of its


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

int main() {
int arr[] = {1, 2, 3, 4, 5};

// Pass array to function


printArr(arr, 5);

return 0;
}

Output
1 2 3 4 5
Explanation: In this example, we pass an integer array arr to the
function printArr(). In the function prototype, we define the array as the array
of integers with no size information.
Here, you may also notice that we have passed the size of the array as
second parameter to the function. It is recommended to pass the size of
the array to the function as another parameter, otherwise we won't know
how many elements to process.
The other ways of passing arrays as pointers include:
Passing as Sized Array
Similar to the above method, we can also define the size of the array while
passing it to the function. But it still will be treated as pointer in the function.
#include <stdio.h>

// Array passed as an array with the size of its


// dimension
void printArr(int arr[5], int n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
}
int main() {
int arr[] = {1, 2, 3, 4, 5};

// Pass array to function


printArr(arr, 5);

return 0;
}

Output
1 2 3 4 5
Explanation: Here, we pass the array arr and its size size to the
function printArray. The function then prints all elements of the array based
on the given size.
Passing Array as Pointer Notation
Instead of using array notation arr[] in the function parameter, we can directly
use pointer notation int *arr. All are equivalent, as arrays in C are treated as
pointers to the first element of the array. This method is more flexible when
working with dynamically allocated arrays.
#include <stdio.h>

// Array passed as an array with the size of its


// dimension
void printArr(int* arr, int n) {
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
}

int main() {
int arr[] = {1, 2, 3, 4, 5};

// Pass array to function


printArr(arr, 5);

return 0;
}

Output
1 2 3 4 5
================================================================

Pass array with call by value method


In the following code, the main() function has an array of integers. A
user−defined function average () is called by passing the array to it. The
average() function receives the array, and adds its elements using a for loop. It
returns a float value representing the average of numbers in the array.
Example
#include <stdio.h>
float average(int arr[5]);
int main(){
int arr[] = {10, 34, 21, 78, 5};
float avg = average(arr);
printf("average: %f", avg);
}
float average(int arr[5]){
int sum=0;
int i;
for (i=0; i<5; i++){
printf("arr[%d]: %d\n", i, arr[i]);
sum+=arr[i];
}
return (float)sum/5;
}

Output
arr[0]: 10
arr[1]: 34
arr[2]: 21
arr[3]: 78
arr[4]: 5
average: 29.600000
In the following variation, the average() function is defined with two arguments,
an uninitialized array without any size specified. The length of the array
declared in main() function is obtained by divising the size of the array with the
size of int data type.

Example
#include <stdio.h>
float average(int arr[], int length);
int main(){
int arr[] = {10, 34, 21, 78, 5};
int length = sizeof(arr)/sizeof(int);
float avg = average(arr, length);
printf("average: %f", avg);
}
float average(int arr[], int length){
int sum=0;
int i;
for (i=0; i<length; i++){
printf("arr[%d]: %d\n", i, arr[i]);
sum+=arr[i];
}
return (float)sum/length;
}
Output
arr[0]: 10
arr[1]: 34
arr[2]: 21
arr[3]: 78
arr[4]: 5
average: 29.600000
Advertisement: 0:04

Pass array with call by reference


To use this approach, we should understand that elements in an array are of
similar data type, stored in continuous memory locations, and the array size
depends on the data type. Also, the address of the 0th element is the pointer to
the array.

In the following example −

int a[5] = {1,2,3,4,5};

The size of the array is 20 bytes (4 bytes for each int)

Int *x = a;

Here x is the pointer to the array. It points to the 0th element. If the pointer is
incremented by 1, it points to the next element.

Example
#include <stdio.h>
int main() {
int a[] = {1,2,3,4,5};
int *x = a, i;
for (i=0; i<5; i++){
printf("%d\n", *x);
x++;
}
return 0;
}

Output
1
2
3
4
5

Let us use this characteristics for passing the array by reference. In the main()
function, we declare an array and pass its address to the max() function. The
max() function traverses the array using the pointer and returns the largest
number in the array, back to main() function.

Example
#include <stdio.h>
int max(int *arr, int length);
int main(){
int arr[] = {10, 34, 21, 78, 5};
int length = sizeof(arr)/sizeof(int);
int maxnum = max(arr, length);
printf("max: %d", maxnum);
}
int max(int *arr, int length){
int max=*arr;
int i;
for (i=0; i<length; i++){
printf("arr[%d]: %d\n", i, (*arr));
if ((*arr)>max)
max = (*arr);
arr++;
}
return max;
}

Output
arr[0]: 10
arr[1]: 34
arr[2]: 21
arr[3]: 78
arr[4]: 5
max: 78

The max() function receives the address of the array from main() in the pointer
arr. Each time, when it is incremented, it points to the next element in the
original array.

The max() function can also access the array elements as a normal subscripted
array as in the following definition −

int max(int *arr, int length){


int max=*arr;
int i;
for (i=0; i<length; i++){
printf("arr[%d]: %d\n", i, arr[i]);
if (arr[i]>max)
max = arr[i];
}
return max;
}
Pass two−dimensional array to function
You can also pass the pointer of a two-dimensional array to a function. Inside
the function, the two dimensional array is traversed with a nested for
loop construct

Example
#include <stdio.h>
int twoDarr(int *arr);
int main(){
int arr[][3]= {10, 34, 21, 78, 5, 25};
twoDarr(*arr);
}
int twoDarr(int *arr){
int max=*arr;
int i, j;
for (i=0; i<2; i++){
for (j=0; j<3; j++){
printf("%d\t", arr[i]);
arr++;
}
printf("\n");
}
}

Output
10 34 21
5 25 16

Function to compare string lengths


In the following program, two strings are passed to compare() functions. In C, as
string is an array of char data type. We use strlen() function to find the length of
string which is the number of characters in it.

Example
#include <stdio.h>
#include <string.h>
int compare( char *, char *);
int main() {
char a[] = "BAT";
char b[] = "BALL";
int ret = compare(a, b);
return 0;
}
int compare (char *x, char *y){
int val;
if (strlen(x)>strlen(y)){
printf("length of string a is greater than or equal to length of string b");
}
else{
printf("length of string a is less than length of string b");
}
}

Output
length of string a is less than length of string b
===================================================================
=

Functions in C help the programmers to adapt modular program design. A


function can be defined to accept one or more than one arguments, it is able to
return a single value to the calling environment. However, the function can be
defined to return an array of values. In C, a function can be made to return an
array by one of following methods −

 Passing the array as argument and returning the pointer


 Declaring a static array in a function and returning its pointer
 Using malloc() function

Embedding the array inside a struct variable and passing it to a function

We implement these methods to calculate the square, the cube and the square
root of a given number.

Pass array by reference


In the following example, we declare an uninitialized array in main() and pass it
to a function, along with an integer. Inside the function, the array is filled with
the square, cube and square root. The function returns the pointer of this array,
using which the values are access and printed in main() function.

Example
#include <stdio.h>
#include <math.h>
int arrfunction(int, float *);
int main(){
int x=100;
float arr[3];
arrfunction(x, arr);
printf("Square of %d: %f\n", x, arr[0]);
printf("cube of %d: %f\n", x, arr[1]);
printf("Square root of %d: %f\n", x, arr[2]);
return 0;
}
int arrfunction(int x, float *arr){
arr[0]=pow(x,2);
arr[1]=pow(x, 3);
arr[2]=pow(x, 0.5);
}
Output
Square of 100: 10000.000000
cube of 100: 1000000.000000
Square root of 100: 10.000000
PauseSkip backward 5 secondsSkip forward 5 seconds
Mute

Fullscreen

Return static array


Instead of passing an empty array from main(), we can declare an array inside
the called function itself, fill it with the required values, and return its pointer.
However, returning a pointer of a local variable is not acceptable, as it points to
a variable that no longer exists. Note that a local variable ceases to exist as
soon as the scope of the function is over. Hence, we need to use a static array
inside the called function (arrfunction) and return its pointer back to main().

Example
#include <stdio.h>
#include <math.h>
float * arrfunction(int);
int main(){
int x=100, i;
float *arr = arrfunction(x);
printf("Square of %d: %f\n", x, *arr);
printf("cube of %d: %f\n", x, arr[1]);
printf("Square root of %d: %f\n", x, arr[2]);
return 0;
}
float *arrfunction(int x){
static float arr[3];
arr[0]=pow(x,2);
arr[1]=pow(x, 3);
arr[2]=pow(x, 0.5);
return arr;
}

Output
Square of 100: 10000.000000
cube of 100: 1000000.000000
Square root of 100: 10.000000

Now, consider the following function which will generate 10 random numbers
and return them using an array and call this function as follows −

Example
#include <stdio.h>
#include <time.h>
#include <stdlib.h>

/* function to generate and return random numbers */


int * getRandom( ) {
static int r[10];
int i;

/* set the seed */


srand( (unsigned)time( NULL ) );
for ( i = 0; i < 10; ++i) {
r[i] = rand();
printf( "r[%d] = %d\n", i, r[i]);
}
return r;
}

/* main function to call above defined function */


int main () {

/* a pointer to an int */
int *p;
int i;
p = getRandom();
for ( i = 0; i < 10; i++ ) {
printf( "*(p + %d) : %d\n", i, *(p + i));
}
return 0;
}

When the above code is compiled together and executed, it produces the
following result −

Output
r[0] = 2110147662
r[1] = 1427553496
r[2] = 1243625529
r[3] = 857484361
r[4] = 513293736
r[5] = 964923407
r[6] = 36104419
r[7] = 1248464892
r[8] = 1838450240
r[9] = 2096489563
*(p + 0) : 2110147662
*(p + 1) : 1427553496
*(p + 2) : 1243625529
*(p + 3) : 857484361
*(p + 4) : 513293736
*(p + 5) : 964923407
*(p + 6) : 36104419
*(p + 7) : 1248464892
*(p + 8) : 1838450240
*(p + 9) : 2096489563

Using malloc() function


The malloc() function is available as a library function in stdlib.h header file. It
dynamically allocates a block of memory during the runtime of a program.
Normal declaration of variables causes the memory to be allocated at the
compile time.

void *malloc(size_t size);

The malloc() function returns a generic void pointer. To assign values of a


certain data type in the allocated memory, it must be typecast to the required
type. For example, to store an int data, it must be typecast to int * as follows −

int *x = (int *)malloc(sizeof(int);

Let us allocate a block of memory sufficient to store three float values


corresponding to square, cube and square root of a number, and return the float
pointer to main(), inside which the computed values are displayed.

Example
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
float * arrfunction(int);
int main(){
int x=16, i;
float *arr = arrfunction(x);
printf("Square of %d: %f\n", x, arr[0]);
printf("cube of %d: %f\n", x, arr[1]);
printf("Square root of %d: %f\n", x, arr[2]);
return 0;
}
float *arrfunction(int x){
float *arr = (float *)malloc(3*sizeof(float));
arr[0]=pow(x,2);
arr[1]=pow(x, 3);
arr[2]=pow(x, 0.5);
return arr;
}

Output
Square of 16: 256.000000
cube of 16: 4096.000000
Square root of 16: 4.000000

Using array element in struct


In this method, we will declare a struct, inside which there is an float array as its
element. The called function (myfunction) declares a struct variable, populates
the array element with square, cube and the square root of the argument
received by it, and returns it to the main() function.

Example
#include <stdio.h>
#include <math.h>
struct mystruct{
float arr[3];
};
struct mystruct myfunction(int x);
int main(){
int x = 9;
struct mystruct s = myfunction(x);
printf("Square of %d: %f\n", x, s.arr[0]);
printf("cube of %d: %f\n", x, s.arr[1]);
printf("Square root of %d: %f\n", x, s.arr[2]);
return 0;
}
struct mystruct myfunction(int x){
struct mystruct s1;
s1.arr[0]=pow(x,2);
s1.arr[1]=pow(x,3);
s1.arr[2]=pow(x, 0.5);
return s1;
}

Output
Square of 9: 81.000000
cube of 9: 729.000000
Square root of 9: 3.000000

Return string from function


Using the same approaches, you can pass and return a string to a function.
A string in C is an array of char type. In the following example, we pass the
string with a pointer, manipulate it inside the function, and return it back to
main().

Inside the called function, there is a local string. The string passed is
concatenated with the local string before returning.

Example
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char * hellomsg(char *);


int main(){
char * name = "TutorialsPoint";
char *arr = hellomsg(name);
printf("%s\n", arr);
return 0;
}
char * hellomsg(char *x){
char *arr = (char *)malloc(50*sizeof(char));
strcpy(arr, "Hello ");
strcat(arr, x);
return arr;
}

Output
Hello TutorialsPoint

You might also like