NO

Author Topic: Const pointer problem  (Read 6805 times)

post from old forum

  • Guest
Const pointer problem
« on: September 13, 2004, 08:47:57 PM »
int main(void) {
const char* str1 = "String1";
char* const str2 = "String2";
char* p = "Testing!";

*str1 = 'X'; // Error: Assignment to const location.
str1 = p; // it works.

*str2 = 'X'; // Oops ...
str2 = p; // Error: Assignment to const identifier 'str2'.

return 0;
}

Hi Pelle, this statement *str2 = 'X'; passed the compilation but the
program crashed. What's wrong with it? It should work, right?

I am using your software to learn Win32API programming now but I have a long time no using C language to program, so I perhaps made some mistakes, thanks for your help again ... Have a nice day!

Barney.

post from old forum

  • Guest
Const pointer problem
« Reply #1 on: September 13, 2004, 08:48:23 PM »
Hello,

The statement *str2 = 'X'; is OK from the compilers point of view. The problem is that str2 contains the address of a literal string ("String2"). When you are assigning to *str2, you are trying to write to the memory area where string literals are stored. This area is always read-only i Pelles C (and some other C compilers). This is a typical case where you can get different results depending on the C compiler used. The best thing is to avoid cases like this...

Pelle