【问题标题】:How to fix argument of type is incompatible with parameter of type如何修复类型参数与类型参数不兼容
【发布时间】:2019-09-21 20:35:11
【问题描述】:

我使用函数isspace 在单词中搜索空格。问题是我在程序构建时收到一条错误消息: "argument of type char* is incompatible with parameter of type int"

    int const bufferSize = 256;

    newItemIDPointer = (char*)malloc(bufferSize * sizeof(char));
    if (newItemIDPointer == NULL)
    {
        printf("Didnt allocate memory!");
        exit(EXIT_SUCCESS);
    }

    printf("Enter new Item ID: ");
    scanf_s(" %[^'\n']s", newItemIDPointer, bufferSize);

    stringLength = strlen(newItemIDPointer);
    newItemIDPointer = (char*)realloc(newItemIDPointer, size_t(stringLength + 1));

    int i = 0;
    int count = 0;
    while ((newItemIDPointer + i) != '\0')
    {
        if (isspace(newItemIDPointer + i))
        {
            count++;
        }
        i++;
    }

我的代码中isspace 的实现有什么问题,我该如何解决这个错误消息?

【问题讨论】:

标签: c isspace


【解决方案1】:

这是因为您的表达式 newItemIDPointer + i 是指向字符串中偏移量 i 的字符的指针,而不是该位置的值(字符)。您需要取消引用指针以获取值,例如:

*(newItemIDPointer + i)

或者更明显的方法是:

newItemIDPointer[i]

解释一下:假设您有一个指向字符串的指针,称为p

char *p = "ABCDE";

假设指针p 恰好有一个值0x4001。那将是字符串中第一个字符的地址,恰好是 A 的字母 ASCII 值(我只是完全编造了这个数字,实际上操作系统和/或编译器确定了实际的内存位置)。 ..

那么,p + 1 将给我们0x4002.. 字母B 的位置。它不是 B 的 ASCII 值,它恰好是十进制的 66 ......这就是你想要传递给 isspace 的东西......存储在那个内存位置的值,而不是内存位置的地址.

对于 C 初学者来说,这是最困难的事情之一,一旦您在脑海中清楚地了解何时操作内存中某个位置的地址以及操作存储在该位置的数据时,剩下的C 语言很简单...

【讨论】:

    【解决方案2】:

    newItemIDPointer + i 是指向字符串中第 i'th 字符的指针。您不需要指针,而是它指向的字符。您需要取消对指针的引用。

    所以替换这个:

    while ((newItemIDPointer + i) != '\0')
    {
        if (isspace(newItemIDPointer + i))
    

    与:

    while (*(newItemIDPointer + i) != '\0')
    {
        if (isspace(*(newItemIDPointer + i)))
    

    或等效:

    while (newItemIDPointer[i] != '\0')
    {
        if (isspace(newItemIDPointer[i]))
    

    【讨论】:

      猜你喜欢
      • 2021-01-07
      • 2018-09-07
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-18
      • 2021-03-08
      相关资源
      最近更新 更多