如何通过函数设置指针引用
在C中,我试图通过将其发送到函数来设置指针的值,但该值不会在函数外部发生变化。 这是我的代码:
#include 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中没有pass-by-reference。如果你提供str
作为C中函数的参数,你总是传递str
的当前值,而不是str
本身。
你可以将str的指针传递给函数:
void foo(char** pstr) { // ... *pstr = new_str; } int main() { // ... foo(&str); }
正如Eiko所说,你的示例代码泄漏了第一个内存分配。 你不再使用它,而且你不再有指针,所以你无法释放它。 这是不好的。
您需要使用指针指向未经测试的指针:
#include void foo(char** str) { char* new_str = malloc(100); memset(new_str, 0, 100); strcpy(new_str, (char*)"new test"); if (str) { /* if pointer to pointer is valid then */ if (*str) /* if there is a previous string, free it */ free(*str); *str = new_str; /* return the string */ } } 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); }
你只是重新分配一个指针,它是foo中的一个局部变量。
如果要复制字符串,请使用strcpy(str, new_str);
您可以将引用传递给指针并重新分配,但这很容易导致内存泄漏并且难以维护。
编辑:对于伪传递参考,请参阅史蒂夫的回答。
我这样做是通过从函数返回指针。 在这种情况下没有理由使用malloc,因此您不必担心释放。
gcc 4.4.3 c89
char* print_test(char *str) { char *new_str = "new_test"; printf("new_str [ %s ]\n", new_str); str = new_str; return str; } int main(void) { char *str = "test"; printf("str [ %s ]\n", str); str = print_test(str); printf("str [ %s ]\n", str); return 0; }