0

I am trying to use the following helper function inside my substitution.c script:

string upper(string key)
{
    int n = strlen(key);
    char key_upper[n];

    for (int i = 0; i < n; i++)
    {
        if (key[i] >= 'a' && key[i] <= 'z')
        {
            key_upper[i] = key[i] - 32;
        }
        else
        {
            key_upper[i] = key[i];
        }
    }
    return key_upper;
}

The whole point of this was to take a string and make every character uppercase. I tried making a separate script with this as the main function and it seems to work when I print key_upper but not when I return it. I get the following error:

clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow    substitution.c  -lcrypt -lcs50 -lm -o substitution
substitution.c:64:12: error: address of stack memory associated with local variable 'key_upper' returned [-Werror,-Wreturn-stack-address]
    return key_upper;
           ^~~~~~~~~
1 error generated.
<builtin>: recipe for target 'substitution' failed
make: *** [substitution] Error 1

Before that, I tried to to set key_upper to key, and then modify the entries that had lowercase characters in them, but when I used this function on a string, it also modified the original string! Either of two things would solve my problem: 1.(Preferred) Fix the script as written. I'm not sure why there is a memory error? I'm not sure what this means. It would be really nice if someone could explain this to me like they would to a child because I am completely lost. 2. Can I make a copy of an existing variable and update the copy without it redefining the original variable?

1 Answer 1

0

Apparently you can make a copy of a string with strcopy. This at least got rid of the error and it now compiles.

You must log in to answer this question.

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