简体   繁体   中英

C++ array as parameter reference by default?

forgive me for asking such a simple question, but I couldn't connect the dots from previous answers on SO or other sites. I have read that arrays are passed by reference by default and elsewhere I have read that arrays decay to pointers when passed into functions. I am trying to pass an array to a function and modify it, but cannot reconcile the previous two statements. I am not sure whether I am passing in a pointer or reference to toBin and whether it even matters. The following code is my attempt at making changes to the b array in the toBin function.

When I print the modified array, I get a whole bunch of unexpected text much bigger than the original allocated array of size 11 eg 1000000000 submarine blahblahblah . My expected output is 1000000000 .

void toBin(int x,char a[]){ //passed by reference by default
    std::cout << a << std::endl;
    for (int i=9;i>=0;i--){
        if(pow(2,i)<=x){
            x=x-pow(2,i);
            a[9-i]='1'; //i-1 because char b[] is zero indexed
        };
    }
}
int main()
{
    char c[]="submarine";
    double combination = pow(2,sizeof(c)-1);
    char b[11]={'0','0','0','0','0','0','0','0','0','0'};
    toBin(512, b);
    for (int i=0;i<combination;i++){
        std::cout << *(b+i) << std::endl;
    }
}

Basically you pass everything to the function well. Thing that broke your output it's loop itself.

double combination = pow(2,sizeof(c)-1);
...

for (int i=0;i<combination;i++){
    std::cout << *(b+i) << std::endl;
}

Your combination variable can have value like 2^8. So you point by *(b+i) to the address going far beyond the allocated array. To repair it you need change your loop to that:

for (int i=0;i< sizeof(b);i++){

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM