在 C 中,我尝试通过将指针发送到函数来设置指针的值,但该值不会在函数外部更改。这是我的代码:
#include <stdio.h>
void foo(char* str) {
char* new_str = malloc(100);
memset(new_str, 0, 100);
strcpy(new_str, (char*)"new test");
str = new_str;
}
int main (int argc, char *argv[]) {
char* str = malloc(100);
memset(str, 0, 100);
strcpy(str, (char*)"test");
foo(str);
printf("str = %s\n", str);
}
我想打印出:
str = new test
但这段代码打印出来:
str = test
任何帮助将不胜感激。提前致谢。
C 中没有传递引用。如果您提供str
作为 C 中函数的参数,您总是传递当前值str
, never str
itself.
你可以通过一个pointer将 str 放入函数中:
void foo(char** pstr) {
// ...
*pstr = new_str;
}
int main() {
// ...
foo(&str);
}
正如 Eiko 所说,您的示例代码泄漏了第一个内存分配。您不再使用它,并且不再有指向它的指针,因此您无法释放它。这不好。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)