1
#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 ?

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39
  • Arrays decay into pointers starting at the address of the array head. Although you can iterate it similarly to an array, since the actual memory address still holds the data, the types have decayed and as such suffer from typing problems. – Frontear Nov 20 '21 at 02:45

2 Answers2

5

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.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
1

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).

Andreas Wenzel
  • 22,760
  • 4
  • 24
  • 39