【问题标题】:Error ISO C++ forbids comparison between pointer and integer错误 ISO C++ 禁止指针和整数之间的比较
【发布时间】:2021-12-30 05:30:20
【问题描述】:

我收到了这个错误:

[错误] ISO C++禁止指针和整数比较[-fpermissive]

我的代码:

#include <stdio.h>

int main()
{
    int i[1];
    
    int r = 4;
    
    {
        printf("enter a number between 1-10\n");
        while (i != r);
        {
        scanf("%d,&i[0]");
        }
        printf("good job\n :)");
    }
}

【问题讨论】:

  • int i[1]; -> int i = 0;scanf("%d,&amp;i[0]"); -> scanf("%d",&amp;i);
  • 另外,在 while 行末尾丢失分号
  • 在任何解决方案对您有任何好处之前,您必须了解指针和 int 之间的区别,或者实际上是任何 Thing指向的指针之间的区别一件事。
  • 如果你调用一个函数,检查它返回什么。 scanf 返回什么?
  • stdio.h 用于 c。在 c++ 中使用 iostream 代替。也 &amp;i 就足够了,你不需要向它添加数组索引

标签: c++


【解决方案1】:

问题是上面代码中的变量iint 的数组,它衰减 指向@987654323 的指针 @ 由于类型衰减。另一方面,变量rint。所以当你写的时候:

while (i != r)

这意味着您正在尝试将指向 int 的指针与 int 进行比较,因此出现上述错误。

解决这个问题,您可以使用以下程序:


#include <iostream>

int main()
{
    int arr[4] = {}; //create an array named arr of size 4 with elements of type int all initialized to 0
    
    //iterate through the array and take input from user 
    for(int &element : arr)
    {
        std::cout << "Enter number:" << std::endl;
        std::cin >> element; 
    }
    
    return 0;
}


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多