0
    string s = get_string();
    string s_lower = s;
    for (int i = 0, n = strlen(s); i < n; i++)
    {
        s[i] = toupper(s[i]);
    }
    for (int i = 0, n = strlen(s_lower); i < n; i++)
    {
        s_lower[i] = tolower(s_lower[i]);
    }

The thing with these lines of code is I don't understand why my string s_lower changes while executing the first loop and the same thing for the second loop. Didn't I create two different variables(strings) ?

    string s = get_string();
    string s_lower[strlen(s) + 1];
    strcpy(s_lower, s);

I'm trying to use strcpy function as it's recommended. But it doesn't work like this. I also tried to initiliaze my string s_lower without any value. Help please ?

Problem fixed:

    string s = get_string();
    string s_lower;
    s_lower = malloc(sizeof strlen(s) + 1);
    strcpy(s_lower, s);
0

No, you created two different char pointers. A string variable is essentially a character pointer that points to the start of a string or a char array. The reason that any changes affect both vars is this line:

         string s_lower = s;

This line assigns the address contained in s to s_lower. Since both vars now contain the same address, they reference the same string.

Also, you should know that the = operator does not copy the contents of a string. If you want to copy a string from one char array to another, you need to use a call to strcpy() or one of its cousins.

Don't worry, this is a common error made by almost all new programmers at least once. (Anyone that says they never did it is lying. ;-) )

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • Thanks. Additionaly, If I added a line like s = "bhjsj"; and use debug50, s_lower still seems like it has the original value of s. What is the reason for this ? – Ali Sarp Mestcioglu Mar 5 '18 at 10:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .