Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Why cannot build range expression passing an array as a function argument and using in a range-for-statement. Thanks for the help

void increment(int v[]){
    // No problem
    int w[10] = {9,8,7,6,5,4,3,2,1,9};
    for(int& x:w){
        std::cout<<"range-for-statement: "<<++x<<"
";
    }

    // error: cannot build range expression with array function 
    // parameter 'v' since parameter with array type 'int []' is 
    // treated as pointer type 'int *'
    for(int x:v){
        std::cout<<"printing "<<x<<"
";
    }

    // No problem
    for (int i = 0; i < 10; i++){
        int* p = &v[i];             
    }
}

int main()
{
    int v[10] = {9,8,7,6,5,4,3,2,1,9};
    increment(v);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
158 views
Welcome To Ask or Share your Answers For Others

1 Answer

Despite appearances, v is a pointer not an array - as the error message says. Built-in arrays are weird things, which can't be copied or passed by value, and silently turn into pointers at awkward moments.

There is no way to know the size of the array it points to, so no way to generate a loop to iterate over it. Options include:

  • use a proper range-style container, like std::array or std::vector
  • pass the size of the array as an extra argument, and interate with an old-school loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...