Assign array to array

后端 未结 6 1054
礼貌的吻别
礼貌的吻别 2021-01-03 23:32

So I am playing around with some arrays, and I cannot figure out why this won\'t work.

int numbers[5] = {1, 2, 3};
int values[5] = {0, 0, 0, 0, 0};
values =          


        
6条回答
  •  天命终不由人
    2021-01-04 00:09

    Array names are constant not modifiable l-value, you can't modify it.

    values = numbers; 
    // ^
    // is array name
    

    Read compiler error message: "error C2106: '=' : left operand must be l-value" an l-value is modifiable can be appear at lhs of =.

    You can assign array name to a pointer, like:

    int* ptr = numbers;
    

    Note: array name is constant but you can modify its content e.g. value[i] = number[i] is an valid expression for 0 <= i < 5.

    Why can't I do like that?

    Basically this constrain is imposed by language, internally array name uses as base address and by indexing with base address you can access content continue memory allocated for array. So in C/C++ array names with be appear at lhs not a l-value.

提交回复
热议问题