Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/react-native/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 如何将字符指针引用传递给函数并返回受影响的值?_C_Pointers - Fatal编程技术网

C 如何将字符指针引用传递给函数并返回受影响的值?

C 如何将字符指针引用传递给函数并返回受影响的值?,c,pointers,C,Pointers,在这段代码中,我向函数测试传递了一个字符指针引用 在函数测试中,我调整malloc大小并将数据写入该地址,然后打印它并得到空值 #include <stdio.h> #include <stdlib.h> void test(char*); int main() { char *c=NULL ; test(c); printf("After test string is %s\n",c); return 0; } void test(char *

在这段代码中,我向函数测试传递了一个字符指针引用 在函数测试中,我调整malloc大小并将数据写入该地址,然后打印它并得到空值

#include <stdio.h>
#include <stdlib.h> 

void test(char*);

int main()
{

 char *c=NULL ;


 test(c);
 printf("After test string is %s\n",c);
 return 0;
}



void test(char *a)
{
 a = (char*)malloc(sizeof(char) * 6);
 a = "test";
 printf("Inside test string is %s\n",a);
}

你不能只是把指针传进来。您需要传递指针的地址。试试这个:

void test(char**);


int main()
{

 char *c=NULL ;


 test(&c);
 printf("After test string is %s\n",c);

 free(c);   //  Don't forget to free it!

 return 0;
}



void test(char **a)
{
 *a = (char*)malloc(sizeof(char) * 6);
 strcpy(*a,"test");  //  Can't assign strings like that. You need to copy it.
 printf("Inside test string is %s\n",*a);
}
原因是指针是按值传递的。这意味着它被复制到函数中。然后用malloc覆盖函数中的本地副本


因此,要解决这个问题,您需要传递指针的地址。

嘿,山姆,您已经在代码中传递了char指针c

 test(c);
但是,您必须将charecter变量的地址发送到何处

 test(&c);

在这里,这会使您的代码有所不同,因此只需在代码中尝试此更改并执行它。

您可能希望在执行时修复内存泄漏。:)您刚刚释放了一个指向字符串文本=>boom的指针。
*a=“测试”行是实际泄漏位置。@Mystical Yeah我也检查了这个东西valgrind工具
 test(&c);