2
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];
4

1 回答 1

6

The reason this does not work is that you are dropping the results of toupper and tolower. You need to assign the results back to the string passed into your function:

if (isupper(str[i])){
    str[i] = tolower(str[i]);
} else if (islower(str[i])){
    str[i] = toupper(str[i]);
}

Note that in order for this to work the str must be modifiable, meaning that a call convert("Hello, World!") would be undefined behavior.

char str[] = "Hello, World!";
convert(str);
printf("%s\n", str);
于 2013-01-19T23:50:30.863 回答