[英]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 . 在第一次检查中,我得到了从索引
0
到argc
的argv
所有值,但是在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.