Assigning one character array to another gives Error. Why?

我只是一个虾纸丫 提交于 2019-12-11 05:09:57

问题


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;
}

回答1:


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;
}



回答2:


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.



来源:https://stackoverflow.com/questions/35920585/assigning-one-character-array-to-another-gives-error-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!