为什么不能使用“="运算符将数组变量直接分配给另一个数组变量? [英] Why can't I assign an array variable directly to another array variable with the '=' operator?
问题描述
为什么下面的赋值不起作用?如果可能的话,我想要一个低级的解释.另外,这是我得到的编译器错误:'char*' 到 'char [20]' 的赋值中的类型不兼容
Why does the following assignment not work? I would like a low-level explanation if possible. Also, here's the compiler error I get: incompatible types in assignment of 'char*' to 'char [20]'
class UCSDStudent {
char name[20];
public:
UCSDStudent( char name[] ) {
//this-> name = name; does not work! Please explain why not
strcopy( this -> copy, copy ); //works
}
};
推荐答案
因为当你有这样的函数调用时 UCSDStudent( char name[] )
只有数组的地址 name
被复制而不是整个数组.这是一个 C\C++ 特性.
Because when you have a function call like this UCSDStudent( char name[] )
only the adress of the array name
is copied instead of the whole array. It is a C\C++ feature.
此外,定义为 char name [20]
的 name
不是可修改的左值.
Furthermore the name
defined as char name [20]
is not a modifiable lvalue.
关于 strcpy
:它会带来未定义的行为,就好像您的源数组没有 NULL 字符一样,它也会将一些垃圾复制到 this->name
.您可以在此处
Regarding strcpy
: it will bring undefined behaivour as if your source array doesn't have a NULL character it will copy some trash to this->name
too. You may read more about strcpy
here
这篇关于为什么不能使用“="运算符将数组变量直接分配给另一个数组变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!