数组名之间可以直接赋值吗

描述

数组之间的赋值能不能直接使用等于号?比如这样的代码。

int main()
{
    int a[5] = {1, 2, 3, 4, 5}; 
    int b[5] = {0};


    b = a;
    
    return 0;
}

想把数组 a 里面的数据全部赋值给 b,写成 b = a 行不行?

和这个问题类似的还有,数组名为什么不能进行 ++ 操作?

char array[5] = {0};
array++;

比如这样的表达式,array++ 在编译的时候就会提示错误:

root@Turbo:~# gcc test.c -o test
test.c: In function ‘main’:
test.c:18:11: error: assignment to expression with array type
   18 |         b = a;
      |           ^
test.c:22:14: error: lvalue required as increment operand
   22 |         array++;
      |              ^~
root@Turbo:~#

需要一个左值作为操作数,换句话说,数组名不能作为左值。

关于数组名,官方的解释是:

/*
 * Except when it is the operand of the sizeof operator, or typeof 
 * operators, 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. If the array object has register storage class, the be
 * havior is undefined.
 * */

除了跟 sizeof、typeof、& 这些运算符一起使用,数组类型通常被转换成指针类型,指向数组的第一个元素,并且它不能作为左值,不能作为左值,也就是不能被修改。

其实也很好理解,数组被初始化后,已经分配了内存,数组名就表示这块内存的地址,如果数组名被修改了,整个数组都要跟着移动,显然不合适。

那 array + 1 这个表达式有没有问题?

当然没有问题,array++ 和 array + 1 是两码事。

array++ 会修改 array 的值,但是 array + 1 只是个表达式,并不会修改 array 的值,如果写成 array = array + 1 才会出问题。

for (int i = 0; i < 5; i++)
{
    b[i] = a[i];
}


//或者 
memcpy(b, a, sizeof(int) * 5);

最后就是关于数组的赋值,在C语言中没有捷径,只能通过循环逐个元素赋值,数组名不能直接赋值。
 

 

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分