0

An element of an array can be changed like this.

#include <stdio.h>
void func(int a[]){
    a[0] = 56;
}
int main()
{
     int a[1]={34};
    func(a);
    printf("%d" ,a[0]); 

    return 0;
}

But when the array is replaced by just 'int a'; it remains unchanged. Or in other words, to change value of 'int a' from outside main(), pointers are required. What is the reasoning behind this? Why can an array be changed from a function without pointers but a simple 'int a' requires a pointer for modification?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

1 Answers1

0

To change an object in a function you need to pass it by reference. Otherwise the function will deal with a copy of the value of the passed object.

In C passing by reference means passing an object indirectly through a pointer to it.

This function declaration

void func(int a[]){
    a[0] = 56;
}

is equivalent to

void func(int *a){
    a[0] = 56;
}

due to adjusting by the compiler a parameter having an array type to pointer type to the array element type.

So in the above function elements of the array are passed in fact by reference. That is having a pointer to the first element of an array and the pointer arithmetic you can change any element of the array.

To change the same way a scalar object you need to pass it through a pointer to it.

To make the difference visible then if you have for example a function like

void func( int value )
{
    value = 56;
}

And in main you have

int x;

func( x );

then the function call may be imagined the following way

void func( /*int value */ )
{
    int value = x;
    value = 56;
}

As you can see it is the local variable value initialized by the value of the variable x that is changed.

On the other have if you have a function like

void func( int value[] )
{
    value[0] = 56;
}

and in main you have

int a[1];

func( a );

then the function call may be imagined the following way

func( &a[0] );

void func( /* int value[] */ )
{
    int *value = &a[0];

    value[0] = 56;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • That is very helpful. thank you! Just a follow up question, why can we not call the function as `func(&a)`. Why does it have to be `func(a)`? Just asking for the sake of uniformity. – Sahil Dec 28 '21 at 10:47
  • @Sahil If a is an array declared like int a[1]; then the expression will have the type int ( * )[1]. SO the function must be declared like void func( int ( *a )[1] ); Of course you can declare such a function and pass the array through the expression &a. – Vlad from Moscow Dec 28 '21 at 10:50