混淆将字符串作为参数传递给C函数

时间:2013-01-19 23:47:32

标签: 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);
}

在函数中,我试图反转字符串中每个字母的大小写。我这样称呼函数:

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

1 个答案:

答案 0 :(得分:6)

这不起作用的原因是您放弃了touppertolower的结果。您需要将结果分配回传递给函数的字符串:

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);