2

我使用 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 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;
}
4

1 回答 1

7

双引号之间的字符串是字符串文字。它们是char不可修改的数组(尝试修改它们会调用未定义的行为)。这就是为什么您应该将指向字符串文字的指针声明为const char *- 这样,如果某些代码错误地尝试写入/修改文字中的字符,编译器将有机会捕获此错误。

于 2013-04-02T05:12:22.597 回答