数组之间的赋值能不能直接使用等于号?比如这样的代码。
int main()
{
int a[5] = {1, 2, 3, 4, 5};
int b[5] = {0};
b = a;
return 0;
}
想把数组 a 里面的数据全部赋值给 b,写成 b = a 行不行?
和这个问题类似的还有,数组名为什么不能进行 ++ 操作?
chararray[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语言中没有捷径,只能通过循环逐个元素赋值,数组名不能直接赋值。
-
代码
+关注
关注
30文章
4941浏览量
73151 -
数组
+关注
关注
1文章
420浏览量
27114
原文标题:数组名之间能否直接赋值
文章出处:【微信号:学益得智能硬件,微信公众号:学益得智能硬件】欢迎添加关注!文章转载请注明出处。
发布评论请先 登录
使用直接寻址方式提高速度
scanf函数介绍
单片机之间可以进行无线数据传输吗
数组的初体验
两台变频器之间如何直接实现数据交换?
罗氏线圈可以直接连接示波器进行测试吗?
matlab appdesigner 表格组件赋值问题,求助
《ESP32S3 Arduino开发指南》第三章 C/C++语言基础
光纤头可以直接转换网线头吗
【硬件方向】名企面试笔试真题:大疆创新校园招聘笔试题
在testbench中如何使用阻塞赋值和非阻塞赋值

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