Open In App

Changing Array Inside Function in C

Last Updated : 03 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

When declaring an array the array name is always called the pointer because in an array name the address of the 0th block(base address) is stored. To change an array in the function we have to pass an array in the function. For this, an array_name is passed to the function in the form of an actual argument.

So an address of the 0th block pass to the function call as an actual argument and this address passes to the formal argument in the function to define the body. 
When an array passes in the function then an original array passed in it. Since an array is passing by reference(address). Then if any changes occur in an array in the form of a formal argument inside the function define body then the implemented changes also occur in an array which define in the main().

Example 1: 

C




// C Program to change an Array in function
#include <stdio.h>
 
// here 'm' is the formal argument
void addval(int m[])
{
    int i;
    for (i = 0; i < 5; i++) {
       
        // adding 10 value to each element
        // of an array
        m[i] = m[i] + 10;
    }
}
// here 'm' is the formal argument
void dis(int m[])
{
    int i;
    for (i = 0; i < 5; i++) {
        printf("%d ", m[i]);
    }
    printf("\n");
}
 
void main()
{
    int a[] = { 11, 12, 13, 14, 15 };
 
    printf("Array before function call\n");
    // function call
    dis(a);
 
    // calling addval function
    addval(a);
 
    printf("Array after function call\n");
 
    dis(a);
}


Output

Array before function call
11 12 13 14 15 
Array after function call
21 22 23 24 25 

Example 2:

C




// C Program to take name as input
// and change it in function
#include <stdio.h>
#include <string.h>
 
// function definition body
// n is the formal argument
void change_upper(char* n)
{
    for (int i = 0; n[i] != '\0'; i++) {
        if (n[i] != ' ') {
           
            // changing the case from
            // lower to upper case
            n[i] = toupper(n[i]);
        }
    }
}
 
void main()
{
    char name[50];
    printf("Enter the Name :\n");
    gets(name);
    printf("The name is %s\n", name);
   
    // function call passing an array "name"
    // in the function
    change_upper(name);
 
    printf("The name after calling the function is %s\n", name);
}


Output:

Enter the Name :
GeeksForGeeks
The name is GeeksForGeeks
The name after calling the function is GEEKSFORGEEKS


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads