在C中将字符串常量读取为非常量变量

时间:2016-06-22 15:30:25

标签: c string constants

const char* string_b10_e2 = {"base 10"}; //base 10

有没有办法读取价值"基数10"在非常量字符串变量? 我知道我不能使用char *,如下所示

char * str,
str =  string_b10_e2; //not allowed

因为它违背了保持字符串不变的承诺 但有没有办法将值读入非常量字符串?

提前致谢。

2 个答案:

答案 0 :(得分:2)

  

有没有办法读取价值"基数10"在非常量字符串中   变量?

您可以使用union

union fake {
    const char *as_const;
    char *as_non_const;
};

union fake x;
x.as_const = string_b10_e2;

然后使用x.as_non_const,但请记住,您无法修改其内容(它仍在只读数据段中)

答案 1 :(得分:2)

使用传统赋值运算符初始化后,不能将字符串赋值给char *指针。

但是,您可以使用strcpy功能。如果将其声明为指针而不是具有固定长度的数组,则还需要为字符串分配内存:

char *str = NULL;
str = malloc(20);
if(str == NULL) return;
strcpy(str, "Hello World!\n")
printf("%s", str);
free(str);
str = NULL;
相关问题