Assign a string literal to a char*(将字符串文字分配给 char*)
问题描述
可能重复:
如何摆脱不推荐将字符串常量转换为 'char*' GCC 中的警告?
Possible Duplicate:
How to get rid ofdeprecated conversion from string constant to ‘char*’warnings in GCC?
这个作业:
char *pc1 = "test string";
给我这个警告:
警告:不推荐将字符串常量转换为 'char*'
warning: deprecated conversion from string constant to 'char*'
虽然这个看起来不错:
char *pc2 = (char*)("test string");
这是一种真正更好的方法吗?
Is this one a really better way to proceed?
注意:由于其他原因,我不能使用 const char*.
Notes: for other reasons I cannot use a const char*.
推荐答案
字符串字面量是 C++ 中的 const char[],可能存储在只读内存中,因此程序会崩溃如果您尝试修改它.将非常量指针指向它是个坏主意.
A string literal is a const char[] in C++, and may be stored in read-only memory so your program will crash if you try to modify it. Pointing a non-const pointer at it is a bad idea.
这篇关于将字符串文字分配给 char*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将字符串文字分配给 char*
基础教程推荐
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- c++ STL设置差异 2022-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
