-1

Here CODE A doesn't give any error where as CODE B gives error saying that assignment to expression of array type,

What actual is the difference between CODE A and CODE B ?

int *input_array(int n)
{
  int *array = malloc(sizeof(int) * n);
  printf("Enter the elements of array: ");
  for (int i = 0; i < n; i++)
      scanf("%d", &array[i]);
  return array;
} 
int main()
{
  int n;
  printf("Enter the no.of elements : ");
  scanf("%d", &n);

  int *array;
  array = input_array(n);     CODE A // successful 
    
  int array2[n];
  array2 = input_array(n);    CODE B // error
}
   
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88
  • 2
    arrays cannot be assigned. You will find this in any decent [c book](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) – bolov Dec 09 '20 at 03:34
  • 1
    Arrays cannot be returned either. There is no way to express it, on account of the automatic conversion of values of array type to pointers. – John Bollinger Dec 09 '20 at 03:50

1 Answers1

3

>> What actual is the difference between CODE A and CODE B ?

Couple of points to remember:

  • Arrays are not pointers. They are different1).

  • In C, array names are non modifiable lvalues2).

Note that, in your code, the input_array() function is returning int pointer and not array. Arrays cannot be returned but you can return pointer to initial element of an array from a function3).

In CODE A, you are assigning input_array() function return value to an int pointer named array. The type of array variable and return type of input_array() function is same. Hence, the assignment is perfectly valid.

CODE B is invalid because you are attempting to assign to array2 which is an array of int type and , in C, array names are non modifiable lvalues. You cannot assign anything to an array variable but can only initialise/modify the array members.


1). Check this.

2). From C11 Standards#6.3.2.1p1 [emphasis added]

.... A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a const-qualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a const-qualified type.

3). When you access an array, it is converted to a pointer to first element but there are few exceptions to this rule:
From C11 Standards#6.3.2.1p3 [emphasis added]

3 Except when it is the operand of the sizeof operator, the _Alignof 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. ....

H.S.
  • 11,654
  • 2
  • 15
  • 32