简体   繁体   English

默认情况下C ++数组作为参数引用?

[英]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. 原谅我提出这样一个简单的问题,但是我无法将SO或其他网站上以前的答案中的点点滴滴连串起来。 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. 我不确定是否要传递指向toBin的指针或引用,甚至是否重要。 The following code is my attempt at making changes to the b array in the toBin function. 以下代码是我尝试在toBin函数中更改b数组的toBin

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 . 当我打印修改后的数组时,得到的一大堆意外文本比原始分配的大小为11的数组大得多,例如1000000000 submarine blahblahblah My expected output is 1000000000 . 我的预期输出是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. 您的combination变量的值可以为2 ^ 8。 So you point by *(b+i) to the address going far beyond the allocated array. 因此,您通过*(b+i)指向的地址远远超出了分配的数组。 To repair it you need change your loop to that: 要修复它,您需要将循环更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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