【问题标题】:*Beginner* C: incompatible integer to pointer conversion passing 'char' to parameter of type 'const char *'*初学者* C:不兼容的整数到指针转换将'char'传递给'const char *'类型的参数
【发布时间】:2013-11-09 07:34:46
【问题描述】:

我正在尝试将字符串中的每个字母转换为它的 ASCII 数字。使用

 int letter = (atoi(ptext[i]));

给我这个错误:

error: incompatible integer to pointer conversion
  passing 'char' to parameter of type 'const char *'; take the
  address with & [-Werror]
    int letter = (atoi(ptext[i]));
                       ^~~~~~~~
                       &
/usr/include/stdlib.h:148:32: note: passing argument to parameter
      '__nptr' here
extern int atoi (__const char *__nptr)

以下是我可能相关的其余代码:

    #include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, string argv[])
{

    printf("Give a string to cipher:\n");
    string ptext = GetString();

    int i = 0;

    if (isupper(ptext[i]))
    {
        int letter = (atoi(ptext[i]));
    }
}

我做错了什么,如何解决这个问题,以便将字符串转换为 ASCII 值?

注意:cs50.h 让我在 main 中使用“string”而不是“char*”。

【问题讨论】:

    标签: c cs50


    【解决方案1】:

    atoi() 需要一个字符串。您只需要字符的字符代码... 这是字符本身, 因为在 C 中,char 就像其他整数一样是普通整数类型,而字符串是数组的chars 自己持有字符代码。

    因此,

    int letter = ptext[i];
    

    会做的。

    【讨论】:

    • @hacks 谢谢! :) 美好的祝愿永远不会迟到。
    【解决方案2】:

    您不需要将字符转换为数字。这是对您的数据的解释问题。

    字符“A”可以被认为是 0x41 或 65,所以这很好:

    int number = 'A';
    

    变量编号的值是 0x41/65 或 1000001b,具体取决于您希望如何呈现/对待它。

    至于解释:如果将 0xFF 显示为无符号值,则可以将其视为 255,如果将其视为有符号并保留为 8 位,则甚至可以视为 -1。

    所以你的问题:

    可以将字符串转换为 ASCII 值吗?

    有点错误 - 字符串的所有字符都已经是 ascii 值 - 这只是你如何对待/打印/解释/呈现它们的问题。

    【讨论】:

      【解决方案3】:
      int letter = (atoi(ptext[i]));
      

      atoi() 将字符串转换为整数而不是字符。

      将字符的 ascii 值存储到整数变量中 将字符直接赋值给整数变量。

      int letter = ptext[i];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-11
        • 2015-03-08
        • 2020-01-20
        • 1970-01-01
        • 1970-01-01
        • 2021-06-29
        • 2021-12-16
        相关资源
        最近更新 更多