3

Before I start I want to tell you I am learning to program.

What is the difference between Passing the variable to function and passing an array to the function in C?

When we pass a variable to function we are just passing the value of function. But when we pass an array we are passing somehow a pointer because when we do some changes on an array inside a function, actual array gets changed.

In order to make my question clear I am attaching code which will explain what I am asking-

Code 1:

//Passing variable to function
#include<stdio.h>
void swap(int x, int y);
int main(void)
{
//Nothing is happening to real values of variables
    int x, y;
    x = 1; 
    y = 2;
    swap(x, y);
    printf("%d = x \n %d = y", x, y);
}

void swap(int x, int y)
{
    int temp;
    temp = x;
    x = y;
    y = temp;
}

Code 2:

//Here you can see the values of arrays are swapped.
#include<stdio.h>
void swap(int arr[]);


int main(void)
{
    int idx, array[2];
    for(idx = 0; idx < 2; idx++ )
    {
        scanf("%d", &array[idx]);
    }
    swap(array);
    for(idx = 0; idx < 2; idx++, printf("\n"))
    {
        printf("%d", array[idx]);
    }
}

void swap(int arr[])
{
    int temp;
    temp = arr[0];
    arr[0] = arr[1];
    arr[1] = temp;
}

Maybe my question is still unclear but I just want to know why the values of the array gets changed in main function as when we call the function we are just passing a function value of that variable.

Roberto Caboni
  • 6,078
  • 10
  • 19
  • 34
  • 4
    It's basically exactly how you say. You pass a variable, then the value of the variable is passed. You pass an array, then the pointer to the first element of the array is passed. So what is your question? – Jabberwocky Apr 15 '20 at 09:48
  • 2
    Because the array is passed as a pointer, the function operates on the array's values directly. The array values are not copied to the function. – Paul Ogilvie Apr 15 '20 at 09:48
  • 1
    Arrays are passed by pointer for two reasons. 1) It saves time. 2) It saves space. Neither of those matter if the array has 2 elements. Both of those matter if the array has 2 million elements. – user3386109 Apr 15 '20 at 09:51
  • You basically got it right. Maybe that [question about array to pointer decay](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay) is interesting for you. – churill Apr 15 '20 at 09:53
  • Note that in the first example you do not swap the values of `x` and `y` in `main()`. You only change `x` and `y` inside of `swap()` which is pretty useless. – RobertS supports Monica Cellio Apr 15 '20 at 10:07

5 Answers5

4

In the both cases when a variable as you are saying is passed to a function or an array is passed to a function there is passed a value.

But in the first case there is passed the value of the variable while in the second case there is passed the value of the pointer to first element of an array.

Arrays used in expressions with rare exceptions are converted to pointers to their first elements.

From the C Standard (6.3.2.1 Lvalues, arrays, and function designators)

3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

So having a pointer to an object you can change the pointed object.

Let's assume that you have two functions.

void f( int x )
{
   x = 10;
}

and

void g( int *px )
{
    *px = 10;
}

and their calls

int n = 0;

f( n );
g( &n );

You can imagine the function definitions and their calls the following way

int n = 0;

f( n );
g( &n );

//...

void f( /* int x */ )
{
   int x = n;
   x = 10;
}

void g( /* int *px */ )
{
    int *px = &n;
    *px = 10;
}

That is the both functions deal with copies of values of the expressions used as function arguments. But in case of the function g as the function gets the value of the address of the pointed object n you can change the pointed object n using the pointer (address).

In the terms of C passing an object to a function indirectly through a pointer to the object is called passing by reference.

From the C Standard

— A pointer type may be derived from a function type or an object type, called the referenced type. A pointer type describes an object whose value provides a reference to an entity of the referenced type. A pointer type derived from the referenced type T is sometimes called ‘‘pointer to T’’. The construction of a pointer type from a referenced type is called ‘‘pointer type derivation’’. A pointer type is a complete object type.

Pay attention to that a function declaration like this

void f( int a[], size_t n );

is equivalent to the following declaration

void f( int *a, size_t n );

And the both declare the same one function.

If you have an array as for example

#define N 10
//...
int a[N];

then it is passed to the function like

f( a, N );

then as it is followed form the first quote from the C Standard the array designator is converted to pointer to its first element. And having this pointer in the function you can change any element of the array because each element of the array in fact is passed by reference. Using the pointer arithmetic you can change any element of the pointed array. For example

void f( int *a, size_t n )
{
    for ( int i = 0; i < n; i++ )
    {
        a[i] = i;
        // that is the same as
        // *( a + i ) = i;
    }
}
Vlad from Moscow
  • 224,104
  • 15
  • 141
  • 268
2

When you pass an array, you are actually passing the base address of the same, which is a pointer to the first array element in the memory. It is inherently a call by reference, so you don't need to explicitly use a reference or & while passing into your swap function. arr decays to &(arr[0]).

On the other hand, variables are not by default passed by value, and you need to explicitly use a & to pass them by reference to get their values swapped in their memory locations and not just specific to the scope of the swap function.

Eric Postpischil
  • 141,624
  • 10
  • 138
  • 247
Anirban166
  • 3,162
  • 4
  • 11
  • 27
2

What is the difference between Passing the variable to function and passing an array to the function in C?

You cannot pass an array as it is to a function. The C syntax does not allow that. When you provide the identifier of an array as argument it decays to a pointer to the first element of the array - so you pass the array by reference to its first element.

If the relative parameter of the function is of the matching pointer type, here int * or int a[], this is permissible.

Instead when providing a variable as argument you pass it by value. Means you do not access the variable provided as argument in the function itself. Rather the value is copied into a local variable of the function.

If you want to change the value of the variable passed itself, you need to use the & ampersand operator to gather the address of the variable itself. This is only permissible if the relative parameter is of matching pointer type as above.


Thus, In the first example you do not swap the values of x and y in main(). You only change x and y inside of swap() which is pretty useless.

If you want to swap xand y in main you need to define swap() as:

void swap(int* x, int* y)
{
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

and call swap() like:

swap(&x, &y);

I suggest you to learn more about pointers.

1

You are not passing the array as copy. It is only a pointer pointing to the address where the first element is in memory.

When passing an array as a parameter, this

void arraytest(int a[])

means exactly the same as

void arraytest(int *a)

so you are modifying the values in main. However in C function arguments are always passed by value. In case of an array (variable), while passed as a function argument, it decays to the pointer to the first element of the array. The pointer is then passed-by-value, as usual.

Lakshitha Wisumperuma
  • 1,245
  • 1
  • 8
  • 13
1

An array is a special variable. When you pass a regular variable to a function as an argument, its value is copied to a local variable pertaining to the function.

When you pass an array to a function as an argument, the address of the first element of the array is copied to a local variable pertaining to the function.

That is basically the difference between passing a regular variable and passing an array to a function.

There is one issue with your perception though. If you want to modify a regular variable to be passed to a function, then you need to pass its address to the function, thus the function should take a pointer type. So just use the pointer notation, i.e int *p as opposed to int p[], even though, they are equivalent as function parameters.

Your code should look like this:

#include<stdio.h>

void swap(int *x, int *y);

int main(void)
{
    int x, y;

    x = 1;
    y = 2;

    swap(&x, &y);
    printf("%d = x \n %d = y", x, y);
}

void swap(int *x, int *y)
{
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}
machine_1
  • 3,863
  • 2
  • 16
  • 39