2013-04-02 2 views
2

으로 변환합니다. cmd를 사용하여 .bat 및 g ++. exe로 컴파일합니다. 누군가 내가 잘못한 것을 말해 줄 수 있습니까? 문자열과 배열에 관한 튜토리얼을 따라 연습 할 때 사용하고 있습니다. 나는 아직도 배우고 있음을 명심하십시오.경고 문자열을 상수에서 char *

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; 
} 
+1

문자열 리터럴은 수정할 수 없으며 유형에 그대로 반영되어야합니다. – chris

+0

@chris Extraneous "them"= P – WhozCraig

+0

@WhozCraig, ... 그리고 유형에 문자열 리터럴을 반영해서는 안됩니다. 그것이 내가 의미했던 것입니다. 나는 "그들"이 합당한 자리 표시 자라고 가정했지만, 어색한 문장이었습니다. – chris

답변

7

문자열은 문자열 리터럴입니다. 그들은 char의 배열로 수정되지 않습니다 (수정하려고 시도하면 정의되지 않은 동작이 호출됩니다). 따라서 문자열 리터럴을 가리키는 포인터를 const char *으로 선언해야합니다. 이렇게하면 일부 코드가 실수로 문자를 리터럴에 쓰거나 수정하려고 시도하면 컴파일러에서이 오류를 catch 할 수 있습니다.

+0

감사합니다. 중복 게시물에 대해 사과드립니다. – Henry

관련 문제