Warm tip: This article is reproduced from stackoverflow.com, please click
c string strcpy

Why does strcpy change the value of this one parameter?

发布于 2020-03-28 23:14:02

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;
}
Questioner
jason96
Viewed
100
Some programmer dude 2020-01-31 17:40

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