[英]Confusion passing string as an argument to C function
void convert(char *str){
int i = 0;
while (str[i]){
if (isupper(str[i])){
tolower(str[i]);
}
else if (islower(str[i])){
toupper(str[i]);
}
i++;
}
printf(str);
}
在函數中,我嘗試反轉字符串中每個字母的大小寫。 我這樣調用該函數:
convert(input);
其中input是char *類型。 我遇到了細分錯誤錯誤。 怎么了
謝謝!
更新:我的輸入來自argv [1]。
char *input;
if (argc !=2){/* argc should be 2 for correct execution */
/* We print argv[0] assuming it is the program name */
printf("Please provide the string for conversion \n");
exit(-1);
}
input = argv[1];
這不起作用的原因是您放棄了toupper
和tolower
的結果。 您需要將結果分配回傳遞給函數的字符串:
if (isupper(str[i])){
str[i] = tolower(str[i]);
} else if (islower(str[i])){
str[i] = toupper(str[i]);
}
請注意,為了使此功能起作用, str
必須是可修改的 ,這意味着調用convert("Hello, World!")
行為將是未定義的。
char str[] = "Hello, World!";
convert(str);
printf("%s\n", str);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.