int array1[] = {1,2,3};
int *array2;
int array3[3];
array2 = array1;//copy pointer only
array3 = &array1;//error
To elaborate, from C11, chapter §6.5.16
assignment operator shall have a modifiable lvalue as its left operand.
and, regarding the modifiable lvalue, from chapter §6.3.2.1
A modifiable lvalue is an lvalue that does not have array type, [...]
You need to use strcpy() to copy into the array.
That said, int array1[] = {1,2,3}; works fine, because this is not a direct assignment involving assignment operator. There we're using a brace-enclosed initializer list to provide the initial values of the object. That follows the law of initialization, as mentioned in chapter §6.7.9
Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.[....]
Byte the way:
printf("address(array1):0x%x\n",&array1);
printf("address(array1+1):0x%x\n",&array1+1);
printf("(array1==&array[0]):0x%x\n",array1);
printf("(&array1[0]+1):0x%x\n",array1+1);
/*
address(array1):0x62fde0
address(array1+1):0x62fdec
(array1==&array[0]):0x62fde0
(&array1[0]+1):0x62fde4
*/
array1 and &array1 have same address: 0x62fde0.BUT array1 represents &array1[0]. &array1 represents the whole array.
本文深入探讨了C语言中数组赋值的常见错误,包括指针赋值与复制的区别,以及如何正确初始化和使用数组。通过实例解释了直接赋值与初始化列表的不同,并详细说明了编译器如何处理数组的初始化过程。
2万+

被折叠的 条评论
为什么被折叠?



