if (r<q)
is comparing the memory addresses of
r
and
q
. When you copy "quit" into the array which contains "red" to start with, the contents of the array is changed but not its location in memory.
Difference between char r[] = "red"; and char *q = "Quit"; |
char r[] = "red";
allocates a char array of 4 chars on the stack which contains "red" plus a null terminator (see note [1] below), whereas
char *q = "Quit";
allocates a char* variable, on the stack, which points to a string ("quit") in the const segment of your executable. This is readonly data, so your program will die if you try to change an element of the string that q points to [2].
Note that this line
char* q = "red";
does not cause q to point to a temporary: it causes q to point at a const string in the const segment of your execuable (as I said above).
Andy
Notes:
[1] Careful! The strcpy on line 11 is copying 5 chars (quit + null terminator) into an array variable (r) which is only 4 chars (or elements) long.
As you didn't specify a length, r will be allocated (on the stack) to be just big enough to store the string "red" plus null terminator, which is 4 chars.
So your copy is causing stack damage!
To avoid this problem, you should specify a length for your array which makes sure there's enough room to work with later.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
|
#include <iostream>
using namespace std;
int main(){
char r[256] = "red"; // all elements after the d will be zeroed for you
cout << r << endl;
strcpy(r, "quit");
cout << r << endl;
strcat(r, " and yellow and green and blue");
cout << r << endl;
return 0;
}
|
[2] In C++ code you should only ever use
const char*
to point to string literals, so the compiler stops you making the mistake of changing an element. (the use of char* in this situation is only allowed to provide backwards compatiblity with old versions of C)