c - 在 gcc 中编译 c 时收到有关强制转换“从指针到不同大小的整数”的警告
问题描述
我正在尝试学习 C,并且正在尝试将 achar
转换为 anint
以提取 ASCII 值。但是,当我尝试在 GCC 中编译它时,会收到以下警告:
warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
ascii = (int) letter;
我正在尝试做一个简单的程序,它要求一个字符,扫描它,然后将其转换为 int 以获取 ASCII 值,打印该值。我已将letter
变量初始化为char*
和ascii
as int
。我已经尝试使用占位符,%s
和%c
变量,但它不起作用。%1s
letter
这是代码:
#include <stdio.h>
char* letter;
int ascii;
int main(){
printf("Please input a charcter:");
scanf("%s", letter);
ascii = (int) letter;
printf("\n The ASCII value of %s is %d.\n", letter, ascii);
}
我期望发生的是"Please input a character:"
打印,然后输入一个字符,例如a
,然后它会打印,例如,“a 的 ASCII 值是 97”。
相反,当我输入某些内容时,它会打印"The ASCII value of (null) is zero."
在编译期间,它会打印出上面列出的错误。这不是应该发生的事情。
我该如何解决这个问题?
解决方案
您不是将 char 转换为 int,而是将指向 char 的指针转换为 int。
int main(){
// define as an actual char, not a char*
char letter;
int ascii;
printf("Please input a character:");
// scan a character, not a string. Pass in the address of the char
scanf("%c", &letter);
ascii = (int)letter;
printf("\n The ASCII value of %c is %d.\n", letter, ascii);
}
推荐阅读
- kubernetes - 为什么在 Nginx Ingress 前面放一个 LoadBalancer 类型的服务
- javascript - 在 javascript 解释器中解析循环
- python - 有没有比 apply() 更有效的方法来检查和替换 Pandas Dataframe 中的行值?
- python - 在迭代python时从剩余数组中找到2个元素的最小差异
- sql-server - 如何将用户定义的表类型值传递给 SQL Server Management Studio 中执行过程的值字段?
- r - 在一个 ggplot 上结合两个数据子集和 GLM 结果
- python - 如何增加熊猫的行高?
- javascript - 无法检索 JSON 帖子的内容
- amazon-web-services - 通过 Amplify 调用 iOS 中预先存在的 Lambda 函数
- r - 尝试将两个日期时间字段拆分为 RStudio 中的单独日期和时间字段