你好我有我的功能:
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中串起来...我不知道你是否理解我。谢谢:))
答案 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;
}