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);
}
In the function, I tried to reverse the case of each of the letters in a string. I called the function like this:
convert(input);
Where input is a type of char *. I got a segmentation fault error. What’s wrong here?
Thank you!
UPDATE:
My input is taken from 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];
The reason this does not work is that you are dropping the results of
toupperandtolower. You need to assign the results back to the string passed into your function:Note that in order for this to work the
strmust be modifiable, meaning that a callconvert("Hello, World!")would be undefined behavior.