1

Why output of this program is always:

example 

example

If i change first line with second in for loop, then output will look like this:

EXAMPLE

EXAMPLE

What i am doing wrong?

string key = "EXAmple";
string ukey = key; 
string lkey = key;

for (int i = 0; i < strlen(key); i++)
{
  ukey[i] = toupper(key[i]); 
  lkey[i] = tolower(key[i]);
}       

printf("%s\n", ukey);
printf("%s\n", lkey);
Eric Fortin
  • 7,533
  • 2
  • 25
  • 33
susi33
  • 207
  • 1
  • 2
  • 4

2 Answers2

5

The definition of string is likely to be char*. Consequently, key, ukey and lkey are actually pointers pointing to exactly the same memory; they are just aliases for the same thing.

Codor
  • 17,447
  • 9
  • 29
  • 56
  • 1
    Isn't writing to a string literal undefined behavior? – Scott Hunter Dec 11 '14 at 19:55
  • Might be; I don't know. – Codor Dec 11 '14 at 19:57
  • 1
    @ScottHunter: Yes, but that doesn't preclude it appearing to work just fine. – Fred Larson Dec 11 '14 at 19:58
  • This answer linked below is good: it might work but causes undefined behaviour, especially if another string shares the same literal. http://stackoverflow.com/questions/2245664/string-literals-in-c – Weather Vane Dec 11 '14 at 19:59
  • The answer seems to be complicated; the discussion here is related http://stackoverflow.com/questions/8718740/in-c-why-cant-i-write-to-a-string-literal-while-i-can-write-to-a-string-ob – Codor Dec 11 '14 at 20:01
2

Here, ukey and lkey are likely both pointers to the same array in memory. In C, an array reference is just a pointer to the first item in the array, and using the [] operator just returns the values at each position of the array (dereferenced).

So, ukey and lkey both refer to the exact same characters.

Sounds like you want to use strcpy() instead of ordinary assignment, or the equivalent for your custom type string.

Or use C++ and its string type.

Patrick Szalapski
  • 8,738
  • 11
  • 67
  • 129