C++ 警告:不推荐将字符串常量转换为字符*
我使用cmd来编译.bat和g++.exe。有人能告诉我我做错了什么吗?我在学习字符串和数组的教程时正在使用它进行练习。请记住我还在学习C++ 警告:不推荐将字符串常量转换为字符*,c++,g++,mingw,C++,G++,Mingw,我使用cmd来编译.bat和g++.exe。有人能告诉我我做错了什么吗?我在学习字符串和数组的教程时正在使用它进行练习。请记住我还在学习 main.cpp: In function 'int main()': main.cpp:6:12: warning: deprecated conversion from string constant to 'char*' [- Wwrite-strings] main.cpp:10:12: warning: deprecated conversion f
main.cpp: In function 'int main()':
main.cpp:6:12: warning: deprecated conversion from string constant to 'char*' [-
Wwrite-strings]
main.cpp:10:12: warning: deprecated conversion from string constant to 'char*' [
-Wwrite-strings]
main.cpp:11:12: warning: deprecated conversion from string constant to 'char*' [
-Wwrite-strings]
Press any key to continue . . .
我的代码:
using namespace std;
#include <iostream>
int main() {
//Asterisk to make the variable an array. Takes 8 bytes of memory (8 characters including spaces).
char *a = "hi there";
//Inside square brackets is the number of bytes of memory to use. More consumtion of resources
char b[500]="hi there";
//For a new line, type \n. For a tab, type \t.
char *c = "Hi There\nFriends!";
char *d = "\t\tHi There Friends!";
//endl will end the line.
cout << a;
cout << b << endl;
cout << c << endl;
cout << d << endl;
}
使用名称空间std;
#包括
int main(){
//星号使变量成为数组。占用8字节内存(8个字符包括空格)。
char*a=“你好”;
//方括号内是要使用的内存字节数。更多资源消耗
字符b[500]=“你好”;
//对于新行,键入\n。对于选项卡,键入\t。
char*c=“你好,朋友们!”;
char*d=“\t\t这里有朋友!”;
//endl将结束该行。
双引号之间的cout字符串是字符串文本。它们是不可修改的char
数组(试图修改它们会调用未定义的行为)。这就是为什么您应该将指向字符串文字的指针声明为const char*
-这样,如果某些代码错误地尝试在文字中写入/修改字符,编译器将有机会捕获此错误。字符串文字不可修改,您的类型应反映它们本身。@chris无关的“它们” =P@WhozCraig,…,并且您的类型不应反映字符串文字本身。这就是我的意思。我认为“它们”是一个合理的占位符,但这是一个有点尴尬的句子。@chris同意(在形式和原因上)。谢谢,我为重复的帖子道歉。