将字符串作为参数传递给C函数
在函数中,我尝试反转字符串中每个字母的大小写。我这样调用函数:将字符串作为参数传递给C函数,c,C,在函数中,我尝试反转字符串中每个字母的大小写。我这样调用函数: 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); } 其中输入是一种字符*。我有一个分
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);
}
其中输入是一种字符*。我有一个分段错误。这里怎么了
谢谢大家!
更新:
我的输入来自argv[1]
convert(input);
这不起作用的原因是您正在删除
toupper
和tolower
的结果。您需要将结果分配回传递给函数的字符串:
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];
请注意,为了使其工作,str
必须是可修改的,这意味着调用convert(“Hello,World!”)
将是未定义的行为
if (isupper(str[i])){
str[i] = tolower(str[i]);
} else if (islower(str[i])){
str[i] = toupper(str[i]);
}
输入的值是多少?请注意,仅调用tolower
实际上并不会更改值-它返回小写值。。。您需要将其写回char*
。input
null是否终止?分段错误可能是由于您试图访问分配区域之外的内存位置造成的。此外,改变套管的一种更简单的方法是应用模量:str[i]=str[i]%0x20
input
是如何初始化的?你不能仅仅假设argv[0]
是一个可写的字符串,在使用它之前先复制它。
char str[] = "Hello, World!";
convert(str);
printf("%s\n", str);