C++为什么这个传递引用的数组会产生运行时错误?

and*_*and 0 c++ pass-by-reference

void pushSynonyms (string synline,  char  matrizSinonimos [1024][1024]){


             stringstream synstream(synline);

             vector<int> synsAux;


             int num;

             while (synstream >> num) {synsAux.push_back(num);}


             int index=0;
             while (index<(synsAux.size()-1)){

                   int primerSinonimo=synsAux[index];
                   int segundoSinonimo=synsAux[++index];
                   matrizSinonimos[primerSinonimo][segundoSinonimo]='S';
                   matrizSinonimos [segundoSinonimo][primerSinonimo]='S';

                   }

           } 
Run Code Online (Sandbox Code Playgroud)

和电话..

char matrizSinonimos[1024][1024];
     pushSynonyms("1 7", matrizSinonimos)
Run Code Online (Sandbox Code Playgroud)

matrizSinonimos通过引用传递给我很重要.

编辑:带走了&&matrizSinonimos.

编辑:运行时错误是:

An unhandled win32 exception occurred in program.exe [2488]![alt text][1]
Run Code Online (Sandbox Code Playgroud)

Joh*_*itb 5

它出什么问题了

代码就像你在那里 - 我找不到一个bug.我发现的唯一问题是,如果你根本没有提供任何数字,那么这部分将造成伤害:

(synsAux.size()-1)
Run Code Online (Sandbox Code Playgroud)

它会从0u中减去一个.这将环绕,因为size()返回无符号整数类型.你将得到一个非常大的值,大约2 ^ 16或2 ^ 32.您应该将整个条件更改为

while ((index+1) < synsAux.size())
Run Code Online (Sandbox Code Playgroud)

您可以尝试在呼叫方面查找错误.通常会发生在此之前的某处发生缓冲区溢出或堆损坏,并且程序因此而在程序中的稍后点崩溃.

其中的参数和参数

关于阵列及其如何通过,我认为你做得很好.虽然,您仍然按值传递数组.也许你已经知道了,但我会重复一遍.你真的传递了一个指向这个数组的第一个元素的指针:

char matrizSinonimos[1024][1024];
Run Code Online (Sandbox Code Playgroud)

2d数组实际上是一个数组数组.该数组的第一个元素是一个数组,指向它的指针是一个指向数组的指针.在那种情况下,它是

char (*)[1024]
Run Code Online (Sandbox Code Playgroud)

即使在参数列表中你说你接受了一个数组数组,编译器一如既往地调整它并使它成为指向这样一个数组的第一个元素的指针.所以实际上,在编译器调整参数类型之后,你的函数有了原型:

void pushSynonyms (string synline,  char (*matrizSinonimos)[1024]);
Run Code Online (Sandbox Code Playgroud)

虽然经常建议,但是您不能将该数组作为a传递char**,因为被调用的函数需要内部维度的大小,以正确地处理右偏移处的子维度.使用char**被调用的函数,然后编写类似的东西matrizSinonimos[0][1],它将尝试将该数组的第一个sizeof(char**)字符解释为指针,并尝试取消引用随机内存位置,然后执行该操作时间,如果它之间没有崩溃.不要那样做.它与您在该数组的外部维度中编写的大小无关.它合理化了.现在,通过引用传递数组并不重要.但如果你愿意,你必须改变整个事物

void pushSynonyms (string synline,  char (&matrizSinonimos)[1024][1024]);
Run Code Online (Sandbox Code Playgroud)

通过引用传递不会传递指向第一个元素的指针:保留所有维度的所有大小,并传递数组对象本身而不是值.