简体   繁体   English

将char **传递给函数,是否不更改其值,还是呢?

[英]Passing char** into a function , doesn't change its values , or does it ?

I'm passing a dynamic allocated variables into a function , and after returning from that function , when I run inputs on the code , some of those inputs makes the program to crash . 我将动态分配的变量传递给一个函数,从该函数返回后,当我在代码上运行输入时,这些输入中的一些使程序崩溃。

As you can see , I test the argv array , twice , once at the end of divide , and another time after I return from divide . 如您所见,我对argv数组进行了两次测试,一次是在divide结束时,另一次是从divide返回之后。 In the first check I get all the values of argv from index 0 to argc , but in the 2nd check (after returning from divide back into main ) index 0 make the for loop to crash . 在第一次检查中,我得到了从索引0argcargv所有值,但是在2nd检查中(从divide返回到main ),索引0使for循环崩溃。

So obviously I'm doing something wrong , any idea what ? 所以很明显我做错了什么,知道吗?

argv =(char**) realloc(argv, (current+1)*sizeof(char*));

This is the likely culprit. 这可能是罪魁祸首。 Calling realloc() can allocate a new (presumably larger) block of memory into which the data from the old block is copied, and then deallocate the old block. 调用realloc()可以分配一个新的(可能更大的)内存块,将旧块中的数据复制到其中,然后取消分配旧块。 The problem isn't that you're changing the value of argv in main() , it's that you're not changing it. 问题不在于您要在main()更改argv的值,而是您没有在更改它。 You're deallocating the block that it points to without updating main()'s argv to point to the new block. 您要取消分配它指向的块,而不会更新main()的argv指向新块。

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

相关问题 将指针传递给函数不会改变其值 - Passing a pointer to a function doesn't change its value 为什么不字符 newWord[45]; 在像 char newWord[45] = ""; 这样的函数开始时有“干净”的值; 做? - why doesn´t char newWord[45]; have "clean" values at the start of a function like char newWord[45] = ""; does? 为什么将char传递给函数会更改其在c中的值? - Why does passing a char to a function change it's value in c? C抱怨将char **值传递给函数,使用char const * const * const,但C ++没有 - C complains about passing char** value to function taking char const*const*const but C++ doesn't 为什么这两个char *变量的值在退出函数后没有更改? - Why are the values of these 2 char* variables didn't change after exit the function? 将R矩阵传递给低级.C函数,访问数组以更改其值 - Passing R matrix to a low-level .C function, accessing the array to change its values 将数组传递给函数会改变其值吗? - Passing an array to a function changes its values? 通过将其指针传递给函数来输出矩阵的值 - Output the values of a matrix by passing its pointer to a function 函数不会改变值 - Function does not change values 为什么char *会导致未定义的行为,而char []不会呢? - Why does char* cause undefined behaviour while char[] doesn't?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM