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

これが機能しない理由は、との結果を削除しているため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);
于 2013-01-19T23:50:30.863 に答える