1

Name of an array is pointer to the first element. So Why one character array cannot be assigned another array ?

#include<stdio.h>
int main()
{
  char str1[]="Hello";
  char str2[10];
  char *s="Good Morning";
  char *q;
  str2=str1;  /* Error */
  q=s; /* Works */
  return 0;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Saket Anand
  • 45
  • 1
  • 10

2 Answers2

7

First of all, Name of an array is not the same as a pointer to the first element. In some cases, the array name decays to the pointer to the first element but in general, they are not the same.

Coming to your problem there, array names are not modifiable lvalues, so they cannot be assigned.

Quoting chapter §6.3.2.1 for C11, Lvalues, arrays, and function designators

[...] 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.

For assignment operator, the LHS should be a modifiable lvalue.

Quoting C11, chapter §6.5.16,

An assignment operator shall have a modifiable lvalue as its left operand.

In your case,

 str2=str1;

str2 is not a modifiable lvalue. Hence, you get the error.

FWIW, to copy the contents, you can use strcpy() from string.h header file.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • But be careful using strcpy! Note that bad things will happen if you execute `strcpy(str2,s);` – FredK Mar 10 '16 at 17:10
2

Arrays in expressions automatically converted to pointer pointing to the first element of the array except for operands of sizeof operator and unary & operator, so you cannot assign to arrays.

Adding #include <string.h> to the head of your code and using strcpy() is one of good ways to copy strings.

#include<stdio.h>
#include<string.h>
int main(void)
{
  char str1[]="Hello";
  char str2[10];
  char *s="Good Morning";
  char *q;
  strcpy(str2, str1);  /* Works */
  q=s; /* Works */
  return 0;
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70