【发布时间】:2019-10-07 22:18:53
【问题描述】:
如何更改 char* string3 全局?
int add_on(void);
char* string1 = "hello ";
char* string2 = "world ";
char* string3 ;
int main(){
add_on();// calling add_on();
printf("%s\n",string3); // print
}
int add_on(){
char * string3 = (char *) malloc(1 + strlen(string1)+ strlen(string2));
strcpy(string3, string1);
printf("This is string 3: %s\n",string3);
strcat(string3, string2);
printf("This is string 3: %s\n",string3);
return 0;
}
This is what I get from the console:
This is string 3: hello
This is string 3: hello world
(null)
Program ended with exit code: 0
为什么它为NULL?当我在 add_on() 内部更改时,如何更改函数中的全局 char*?
【问题讨论】:
-
char * string3 =->string3 = -
您正在用另一个同名的局部范围变量覆盖全局范围的
string3。 -
非常感谢,那是我的错
-
请在答案中填写并标记。它将帮助其他有类似问题的人。并且不需要阅读已回答的问题,从而节省我们的时间。