Originally posted by Black-Hearted
Hello again,
Ran into a problem with the following, maybe someone can explain.
char* str="abc";
*(str+0) = *(str+2); //Program Dumps
or
char temp[]="abc";
char* str = temp;
*(str+0) = *(str+2); // no problem
Above values mean nothing but I dont understand why the first one does'nt act the same as the second. Our book says either of these are valid declarations:
char str[SIZE]="abc";
or
char* str="abc";
The original problem was to output the reverse a string using pointers without having [ or ] anywhere in your program. The assignment is done as my instructor informed me that I did'nt have to "reconstruct" the string, but any help understanding the above would be greatly appreciated.
BH
The second one creates a new array, called temp, on the stack. Temp will have 4 bytes allocated to it, and the string literal "abc\0" will be copied to it. It exists on the stack, which has read/write access. When the variable goes out of scope, the 4 bytes are deallocated and removed. It creates a pointer, also on the stack, which points at the other stack variable.
The first creates a pointer on the stack. This pointer is initialized with the address of a string literal (in whatever data segment the compiler puts literals in). Now, it's completely compiler-specific whether this memory is writeable. It will be readable, that much is assured. But writing to this is a bad idea; the compiler is allowed to make it read-only if it wants to (and often does). Further, the compiler is allowed to make strings overlap -- e.g. say you had this:
char * cp1 = "abc";
char * cp2 = "abc";
char * cp3 = "bc";
the compiler is allowed, but not required, to do something like this:
Code:
//Somewhere in a data segment
// [Address] : Data
[BASE_ADDR ] : 'a'
[BASE_ADDR + 1] : 'b'
[BASE_ADDR + 2] : 'c'
[BASE_ADDR + 3] : '\0'
// On the stack
// Variable : contents
cp1 : BASE_ADDR
cp2 : BASE_ADDR
cp3 : BASE_ADDR + 1
In that case, modifying one string could modify two others as well. It's never legal code to write to a string literal; whether it works or not is a matter of choice of a compiler manufacturer. Sometimes you can even get it to work in one compiler mode but not another (e.g. it may error in a debug build but not in a release).
In any event, never write to a string literal. Bad karma.
Technically, a string literal should be a const char *, but for compatibility it auto-converts to a char *, but you shouldn't use this. E.g. you should do things like:
const char * filename = "myfile.txt"