关于函数入参为指针的问题!(语言-c++、c)

初学者提问
函数入参为指针的问题
我定义了两个功能一样的函数,只是一个返回指针,一个返回int值,传入的参数是一个char 类型指针,我在函数里使用malloc在堆上开辟了空间,并使用snprintf往里面写了东西,为啥在主函数中打印传入的指针还是NULL啊,子函数运行完,堆上的内存没释放啊,难道是子函数运行完指针又指向了其他地方?怎么感觉和值传递一样?这要怎么解决,只能返回这个指针类型吗?
代码如下:

#include <iostream>
#include <stdio.h>
using namespace std;

int fun2(char *s)
{
    if (NULL != s)
    {
        free(s);

    }
    s = (char *)malloc(sizeof(char) * 10);
    snprintf(s, 10, "012345%s", "sfd");
    return 1;
}

char* fun3(char *s)
{
    if (NULL != s)
    {
        free(s);

    }
    s = (char *)malloc(sizeof(char) * 10);
    snprintf(s, 10, "012345%s", "ly");
    return s;

}

int main()
{
    char* s = NULL;
    //const char* v = "ds";
    //fun2(s);
    //cout << "fun2:"<<s << endl;
    fun3(s);
    printf("%s", s);
    cout <<endl<< "fun3:" << fun3(s) << endl;
    if (NULL != s)
    {
        free(s);

    }
    return 0;

}

结果:

img

我定义了两个功能一样的函数,只是一个返回指针,一个返回int值,传入的参数是一个char 类型指针,我在函数里使用malloc在堆上开辟了空间,并使用snprintf往里面写了东西,为啥在主函数中打印传入的指针还是NULL啊,子函数运行完,堆上的内存没释放啊,难道是子函数运行完指针又指向了其他地方?怎么感觉和值传递一样?这要怎么解决,只能返回这个指针类型吗?

你对指针理解的还不够透彻,什么时候用到指针传参?要修改外部变量,比如说想修改int类型的变量,参数应该是int*。而你现在需要修改char*类型的变量,需要什么参数?那肯定不能是char*了吧,应该是char**。

函数中分配的内存不能通过参数带出去,可以通过返回值带出去。
也就是s=fun3(s)的方式

第36行:fun3(s); 修改为: s = fun3(s);
或者第37行改为:printf("%s", fun3(s));
或者改函数fun3(),供参考:

#include <iostream>
#include <stdio.h>
using namespace std;

int fun2(char *s)
{
    if (NULL != s)
    {
        free(s);

    }
    s = (char *)malloc(sizeof(char) * 10);
    snprintf(s, 10, "012345%s", "sfd");
    return 1;
}

char* fun3(char**s)  //修改
{
    if (NULL != (*s))
    {
        free((*s));
    }
    (*s) = (char *)malloc(sizeof(char) * 10);
    snprintf((*s), 10, "012345%s", "ly");
    return (*s);
}

int main()
{
    char* s = NULL;
    //const char* v = "ds";
    //fun2(s);
    //cout << "fun2:"<<s << endl;
    fun3(&s);   //修改
    printf("%s", s);
    cout <<endl<< "fun3:" << fun3(&s) << endl; //修改
    if (NULL != s)
    {
        free(s);
    }
    return 0;
}


可以看下c语言参考手册中的 c语言-指针