作为参数的指针为空,但在函数指针不为空之后

时间:2014-06-02 12:32:51

标签: c string pointers

你好我有我的功能:

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中的字符串函数show中串起来...我不知道你是否理解我。谢谢:))

1 个答案:

答案 0 :(得分:3)

您正在按值传递字符串。你需要通过地址传递它:

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