susi33
susi33

Reputation: 209

Why tolower() affecting other string?

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);

Upvotes: 1

Views: 66

Answers (2)

Patrick Szalapski
Patrick Szalapski

Reputation: 9439

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.

Upvotes: 2

Codor
Codor

Reputation: 17605

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.

Upvotes: 5

Related Questions