【问题标题】:how to change the char* global?如何更改 char* 全局?
【发布时间】: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
  • 非常感谢,那是我的错
  • 请在答案中填写并标记。它将帮助其他有类似问题的人。并且不需要阅读已回答的问题,从而节省我们的时间。

标签: c string pointers char


【解决方案1】:

正如 cmets 中已经指出的,string3 不得在 add_on() 函数内再次声明。

Here 是关于 C 中变量范围的一些背景知识。

除此之外,在终止之前free 分配的内存并从main 返回一个值会更干净。

int add_on(void);
char* string1 = "hello ";
char* string2 = "world ";
char* string3;

int main()
{
    add_on(); // calling add_on();
    printf("%s\n", string3); // print
    free(string3);
    return 0;
}

int add_on()
{
    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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-16
    • 2015-08-31
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-23
    相关资源
    最近更新 更多