Home > Mobile >  Why can I assign a value to an array in one case, but not in another?
Why can I assign a value to an array in one case, but not in another?

Time:11-20

#include<stdio.h>

void func(int a[10]);

int main(void) {
    int arr[10];
    func(arr);
    return 0;
}

void func(int a[10]) {
    int b[10], x=5;
    a =&x;
    b =&x; //error: assignment to expression with array type
}

In this C code mentioned herewith, there is an error with b=&x since assignment to expression with array type but why not with a=&x after all a is an array to func ?

CodePudding user response:

Because a is not an array (despite the superficially similar declaration), it is a pointer. You can't declare arguments to functions as arrays in C, and if you do, the compiler silently changes them into pointers for you.

CodePudding user response:

In the function prototype

void func ( int a[10] )

the array a decays to a pointer, because in C, you cannot pass arrays as function arguments. It is therefore equivalent to the following:

void func( int *a )

When calling

func(arr);

in the function main, the array arr will decay to a pointer to the first element of the array, i.e. to &arr[0].

Consequently, the line

a =&x;

is valid, because a is not an array, but simply a pointer, and assigning a new address to a pointer is allowed.

However, the line

b =&x;

is not valid, because b is a real array and you cannot assign values to an entire array (you can only assign values to its individual elements).

  • Related