如何将字符指针引用传递给函数并取回受影响的值? [英] How can I pass character pointer reference to function and get affected value back?

查看:55
本文介绍了如何将字符指针引用传递给函数并取回受影响的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In this code I passed a character pointer reference to function test and in function test I malloc size and write data to that address and after this I print it and got null value.

#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);
}

输出:

Inside test string is test
After test string is (null)

推荐答案

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

You can't just pass the pointer in. You need to pass the address of the pointer instead. Try this:

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 覆盖函数内的本地副本.

The reasoning is that the pointer is passed by value. Meaning that it gets copied into the function. Then you overwrite the local copy within the function with the malloc.

所以为了解决这个问题,你需要传递指针的地址.

So to get around that, you need to pass the address of the pointer instead.

这篇关于如何将字符指针引用传递给函数并取回受影响的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆