You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++报错:ISO C++禁止指针与整数比较 [-fpermissive] 求助

解决“ISO C++ forbids comparison between pointer and integer”报错

错误根源分析及修复步骤

1. 标准C++不支持变长数组(VLA)

代码中int board[height][width];的width是函数参数(运行时确定值),标准C++不允许用变量作为数组维度定义静态数组。编译器会将这类数组解析为指针数组,后续元素访问时就会触发“指针与整数比较”的错误。

修复方法:用vector动态分配二维数组替代静态数组:

vector<vector<int>> board(height, vector<int>(width, blank));

2. 内层for循环语法错误

内层循环写成了for(int j=0;j++;j<width),完全不符合for(初始化; 循环条件; 增量)的标准结构,会导致循环逻辑混乱,触发越界访问或类型错误。

修复方法:修正为正确的循环结构:

for(int j=0; j < width; j++)

3. 数组访问越界问题

当j=0时,j-1=-1;当j=width-1时,j+1=width,这两种情况访问数组都会越界,引发未定义行为,可能导致类型错误或程序崩溃。

修复方法:判断前先检查索引合法性:

if(j > 0 && j < width-1 && board[y][j-1]==dot && board[y][j+1]==blank)

4. 逻辑错误:误用比较运算符

代码中board[y+1][j]==board[y][j];是比较操作,无任何赋值效果,属于逻辑bug。

修复方法:改为赋值操作:

board[y+1][j] = board[y][j];

5. 行、列索引混淆

初始化循环中board[i][0]=blank;的i遍历范围是width,但数组第一维是height(行),当width>height时会触发越界。

修复方法:调整为遍历行索引:

for(int i=0;i<height;i++) {
    board[i][0] = blank;
}

修复后的完整代码

#include <bits/stdc++.h>
using namespace std;

const int height = 50;
int stone = 1;
int dot = 2;
int blank = 0;

void draw(int x, int t)
{
    int width = x;
    vector<vector<int>> board(height, vector<int>(width, blank));

    for(int i=0;i<height;i++)
    {
        board[i][0]=blank;
    }
    
    if(t >=0 && t < height) {
        board[t][0]=dot;
    }

    for(int y=0;y<height-1;y++) {
        for(int j=0;j<width;j++)
        {
            if(j > 0 && j < width-1 && board[y][j-1]==dot && board[y][j+1]==blank)
            {
                board[y+1][j-1]=stone;
                board[y+1][j+1]=stone;
            }
            else 
            {
                board[y+1][j] = board[y][j];
            }
            cout<<board[y+1][j];
        }
        cout << endl;
    }
}

内容的提问来源于stack exchange,提问作者blobaben

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 06:05:21