首页 > 解决方案 > 在 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*asciias int。我已经尝试使用占位符,%s%c变量,但它不起作用。%1sletter

这是代码:

#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." 在编译期间,它会打印出上面列出的错误。这不是应该发生的事情。

我该如何解决这个问题?

标签: c

解决方案


您不是将 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);
}

推荐阅读