jason96
jason96

Reputation: 57

Why does strcpy change the value of this one parameter?

Hi this code I created capitalizes lower case letters. strcpy manages to copy the value of string to stringTwo, however I was wondering why strcpy changes the value of string as well if I just used it as a parameter. Thanks

#include <stdio.h>
#include <string.h>

char *capitalize(char *str) {

    int i;
    for (i = 0; i < strlen(str); i++) {

        if (str[i] >= 97 && str[i] <= 122) {

            str[i] -= 32;

        }

    }

    return str;
}

int main() {

    char string[21];
    char stringTwo[21];

    printf("Enter string: ");
    scanf("%20s", string);

    strcpy(stringTwo, capitalize(string));

    printf("\n%s\ncapitalized: %s", string, stringTwo);

    return 0;
}

Upvotes: 0

Views: 240

Answers (2)

mkde
mkde

Reputation: 17

Because you are changing the original one ( which is "string") and copying it to the new one (which is stringTwo).

If you have a chance for using a debugger, then you will see that in the first place you are changing the "string".

Edit: Or you can try this if you prefer: I changed the code a little bit.

    char *capitalize(char *str,char *str2) {
    strcpy(str2, str);
    int i;
    for (i = 0; i < strlen(str2); i++) {

        if (str2[i] >= 97 && str2[i] <= 122) {

            str2[i] -= 32;

        }

    }

    return str2;
}

With this little change in your function, you are doing all the work in the function. You just type the capitalize(string,stringTwo);and this will do what you've wanted.

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409462

The problem is that the capitalize function converts all letters to upper-case in place. That is, the string you pass as argument will be the one being converted.

If you don't want the original string to be modified, you need to do it in two steps:

strcpy(stringTwo, string);  // First copy the original string
capitalize(stringTwo);  // Then make all letters upper-case in the copy

Upvotes: 2

Related Questions