参数指针为空,但函数指针不为空 [英] Pointer as parameter is null but after function pointer is not null

查看:141
本文介绍了参数指针为空,但函数指针不为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我的功能类似于:

hello i have my funcion like:

void enterString(char *string) {

    string = (char*)malloc(15);

    printf("Enter string: ");
    scanf("%s",string); //don't care about length of string now
}

int main() {
   char *my_string = NULL;
   enterString(my_string);

   printf("My string: %s\n",my_string); /* it's null but i want it to 
                                          show string i typed from 
                                           enterString */

   return 0;
}

我想从显示在main中的字符串上的函数中提取字符串...我不知道您是否会理解我.谢谢:)

I want to string from function show on string in main ... I don't know if you'll understand me. Thank you :)

推荐答案

您正在按值传递字符串.您希望通过地址传递它:

You are passing string by value. You neet to pass it by address :

void enterString(char **string) {

    *string = (char*)malloc(15);

    printf("Enter string: ");
    scanf("%s",*string); //don't care about length of string now //you should!
}

int main() {
   char *my_string = NULL;
   enterString(&my_string);

   printf("My string: %s\n",my_string);

   free(my_string);

   return 0;
}

这篇关于参数指针为空,但函数指针不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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