Page 1 of 1

This should work right??!?

PostPosted: Jul 27, 2001 @ 3:34pm
by RwGast
     <br>char* Test = "Test";<br>*(Test) = 'w';<br><br>Should make the T = w right?! well this code crashes dos and the debugger says that its the <br>*(Test) = 'w'; line. Is there somthing i am doing wrong? this technique works fine if i use an array like char Test[]="Test"; but not when i use a pointer.

Re: This should work right??!?

PostPosted: Jul 27, 2001 @ 4:21pm
by Dan East
First off, are you building for Windows CE or for a desktop machine? If the former, then you should be using Unicode. Second, there is a big difference between:<br><br>[fixed]char *Test="Test";[/fixed]<br><br>and<br><br>[fixed]char Test[]="Test";[/fixed];<br><br>In the first you are creating a pointer called Test. What does it point to? The constant string "Test". You are not supposed to modify const values, hence it may crash.<br>In the second example you create an array of characters, and the compiler automatically makes it large enough to hold the string you want to initialize it with. So when you modify that first character, you are simply modifying the first value in the array you created.<br>Make sense?<br><br>Dan East

Re: This should work right??!?

PostPosted: Jul 27, 2001 @ 4:50pm
by RwGast
how come the value of *Test is constant i did not define it as const char* Test = "Test"; also in the prevous thread of is this bad code? Fredrick used an example of changing the value of a string declared like that. Thats what made me think it was possible.

Re: This should work right??!?

PostPosted: Jul 27, 2001 @ 8:59pm
by Digby
From the ANSI ISO C++ spec, <br><br>2.13.4 String literals<br><br>2. Whether all string literals are distinct (that is, stored in nonoverlapping objects) is implementation defined. The effect of attempting to modify a string literal is undefined.<br><br>Looks like in your situation "undefined" means access violation because the string literal is probably stored in a read-only protected section of memory.<br><br><br><br><br>