Changing Array Inside Function in C
Last Updated :
03 Nov, 2022
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
#include <stdio.h>
void addval( int m[])
{
int i;
for (i = 0; i < 5; i++) {
m[i] = m[i] + 10;
}
}
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" );
dis(a);
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
#include <stdio.h>
#include <string.h>
void change_upper( char * n)
{
for ( int i = 0; n[i] != '\0' ; i++) {
if (n[i] != ' ' ) {
n[i] = toupper (n[i]);
}
}
}
void main()
{
char name[50];
printf ( "Enter the Name :\n" );
gets (name);
printf ( "The name is %s\n" , name);
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
Share your thoughts in the comments
Please Login to comment...