Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why can I assign a string literals to a char* pointer [duplicate]

Tags:

c++

visual-c++

I think the string literals in c++ is the type of const char*. And you can't assign const char* object to a non-constant char* object. But in Visual studio 2010. The following code can compile without errors or warnings, which will however yield a runtime error.

int main(void)
{      
    char *str2 = "this is good";
    str2[0] = 'T';
    cout << str2;
    getchar();
    return 0;
}

And if we don't modify the value of the string, reading the value is ok:

for(char *cp = str2; *cp !=0; ++cp) {
    printf("char is %c\n", *cp);
}
getch();
return 0;

So why can we assign a const char* to a char* here?

like image 605
Joey.Z Avatar asked Mar 25 '23 08:03

Joey.Z


2 Answers

The question is under VC++, but in GCC it has a meaningful warning:

warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

This warning implies that compiler will apply an implicit conversion despite const/non-const differences. So, this code is OK (without any modification in run-time):

char *str2 = "this is good";

However modifying str2 yields an undefined behavior.

like image 181
masoud Avatar answered Apr 02 '23 03:04

masoud


String literals are, indeed, constant. However, arrays decay to pointers, and you took the non-const pointer to the first element in the array:

char *str2 = "this is good";

Modifying any value of the const char array yields undefined behavior.

This will not compile clean under gcc 4.7.2. If you turn the warning levels up to Warning Level 4 under MSVC, it likely will emit a warning there, too.

like image 27
John Dibling Avatar answered Apr 02 '23 03:04

John Dibling