【问题标题】:Passing argument 1 of 'toupper' makes integer from pointer without a cast传递 'toupper' 的参数 1 从指针生成整数而不进行强制转换
【发布时间】:2021-11-27 02:40:24
【问题描述】:

这段代码是一个简单的“转换为大写”程序,但是,当我编译时,我得到了上面标题的错误。有什么解决办法吗?

char *input = argv[1];
printf("%s\n", input);
char toUpper = ("%s\n",toupper(input));
printf("%s\n", toUpper);

【问题讨论】:

  • char toUpper = ("%s\n",toupper(input)); 这应该是什么?
  • toupper() 的参数必须是单个字符。但input 是指向字符的指针,而不是字符。
  • 您的printf 代码似乎与toUpper 的分配混合在一起。
  • 您是想将整个参数转换为大写,还是只是第一个字符?如果要转换整个参数,则需要遍历字符,因为 toupper() 一次只能处理一个字符。
  • 你需要复习一下字符串和字符的区别。

标签: c pointers casting string.h


【解决方案1】:

toupper() 只做一个 char (int)。
你需要做每一个字符...

for (char *x=input, *x, x++) *x = toupper(*x);

这改变了字符串,所以然后像以前一样打印。

printf("%s\n", input);

【讨论】:

  • 严格来说应该是toupper((unsigned char)*x),见stackoverflow.com/questions/21805674/…
  • @NateEldredge 更严格,s/b toupper(*(unsigned char *)x) 正确处理用过时的非 2 补码编码的负值。
猜你喜欢
  • 2011-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-19
  • 2019-02-18
  • 1970-01-01
  • 2021-08-13
相关资源
最近更新 更多