數(shù)組之間的賦值能不能直接使用等于號?比如這樣的代碼。
int main() { int a[5] = {1, 2, 3, 4, 5}; int b[5] = {0}; b = a; return 0; }
想把數(shù)組 a 里面的數(shù)據(jù)全部賦值給 b,寫成 b = a 行不行?
和這個(gè)問題類似的還有,數(shù)組名為什么不能進(jìn)行 ++ 操作?
chararray[5]={0}; array++;
比如這樣的表達(dá)式,array++ 在編譯的時(shí)候就會提示錯(cuò)誤:
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:~#
需要一個(gè)左值作為操作數(shù),換句話說,數(shù)組名不能作為左值。
關(guān)于數(shù)組名,官方的解釋是:
/* * 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、& 這些運(yùn)算符一起使用,數(shù)組類型通常被轉(zhuǎn)換成指針類型,指向數(shù)組的第一個(gè)元素,并且它不能作為左值,不能作為左值,也就是不能被修改。
其實(shí)也很好理解,數(shù)組被初始化后,已經(jīng)分配了內(nèi)存,數(shù)組名就表示這塊內(nèi)存的地址,如果數(shù)組名被修改了,整個(gè)數(shù)組都要跟著移動(dòng),顯然不合適。
那 array + 1 這個(gè)表達(dá)式有沒有問題?
當(dāng)然沒有問題,array++ 和 array + 1 是兩碼事。
array++ 會修改 array 的值,但是 array + 1 只是個(gè)表達(dá)式,并不會修改 array 的值,如果寫成 array = array + 1 才會出問題。
for (int i = 0; i < 5; i++) { ????b[i]?=?a[i]; } //或者? memcpy(b,?a,?sizeof(int)?*?5);
最后就是關(guān)于數(shù)組的賦值,在C語言中沒有捷徑,只能通過循環(huán)逐個(gè)元素賦值,數(shù)組名不能直接賦值。
-
代碼
+關(guān)注
關(guān)注
30文章
4900瀏覽量
70715 -
數(shù)組
+關(guān)注
關(guān)注
1文章
420瀏覽量
26539
原文標(biāo)題:數(shù)組名之間能否直接賦值
文章出處:【微信號:學(xué)益得智能硬件,微信公眾號:學(xué)益得智能硬件】歡迎添加關(guān)注!文章轉(zhuǎn)載請注明出處。
發(fā)布評論請先 登錄
matlab appdesigner 表格組件賦值問題,求助
在testbench中如何使用阻塞賦值和非阻塞賦值

評論