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

sam*_*m_k 8 c pointers

在这段代码中,我传递了一个字符指针引用函数test,并在函数test I malloc size中写入数据并将数据写入该地址,然后打印出来并得到null值.

#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);
}
Run Code Online (Sandbox Code Playgroud)

输出:

Inside test string is test
After test string is (null)
Run Code Online (Sandbox Code Playgroud)

Mys*_*ial 17

你不能只是传入指针.你需要传递指针的地址.试试这个:

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);
}
Run Code Online (Sandbox Code Playgroud)

原因是指针是按值传递的.这意味着它被复制到函数中.然后使用malloc覆盖函数内的本地副本.

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