【问题标题】:problems with convert const char* to char* in c在 c 中将 const char* 转换为 char* 的问题
【发布时间】:2012-03-22 08:55:10
【问题描述】:
int A(const char* name){     
    name = "Here you GO!";    
    char* new_name;      
    //strcpy(new_name,name);      
    new_name = const_cast<char *>(name);      
    printf("%s\n", new_name);      
    return 0;    
}

这是我正在测试的源代码。

一个问题是当我使用const_cast&lt;char *&gt; 时,它说它是未声明的。 (我知道它可以在 'g++' 编译下工作) 另一个问题是当我尝试使用strcpy 将它们组合在一起时,它会弹出分段错误。 前提是我必须使用gcc whatevername.c -std=c99来编译。

有没有人提供一些建议如何解决这个问题。非常感谢..

【问题讨论】:

  • 如果你看到const_cast&lt;char *&gt;g++, but not under gcc`的C编译器部分下工作,你就有证据表明它是C++而不是C......

标签: c char constants


【解决方案1】:

你遇到了分段错误,因为 new_name 没有指向任何地方。

解决方案:为 new_name 分配内存。你可以调用 malloc() 然后使用 strcpy(),或者调用 strdup() 来为你做这两件事:

int A(const char* name){ 
    name = "Here you GO!";

    char* new_name = strdup(name);

    printf("%s\n", new_name);
    return 0;
}

有关 strdup() 的更多详细信息,请参阅此答案:https://stackoverflow.com/questions/252782/strdup-what-does-it-do-in-c

【讨论】:

    【解决方案2】:

    您需要为新字符串分配空间。使用 strcpy 时您走在正确的轨道上,因为 const_cast 仅是 C++。编辑:更好地使用strdupas Miroslav 建议。

    int A(const char* name)
    { 
        name = "Here you GO!";
        char* new_name = malloc(strlen(name)+1);
        if (new_name) {
            strcpy(new_name,name);
            printf("%s\n", new_name);
        }
        return 0;
    ]
    

    【讨论】:

      【解决方案3】:

      您还没有为 new_name 分配空间。分配足够的空间来容纳您要复制到其中的字符串。

      【讨论】:

        【解决方案4】:

        const_cast 是 C++ 的东西;它在 C 中不存在。

        如果你想使用strcpy,你不能只使用未初始化的指针(即new_name)。您需要先分配足够的空间(使用malloc),然后在使用完后分配足够的空间free

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-12-31
          • 2012-01-16
          • 1970-01-01
          • 1970-01-01
          • 2014-10-22
          • 2019-11-11
          • 2020-08-04
          • 2015-04-02
          相关资源
          最近更新 更多