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

使用指针实现的二维数组为何出现错误值?

动态二维数组初始化问题修复

你的代码出现随机崩溃、特定输入必错的核心原因是数组越界访问:在dynamicArray函数中,你错误地使用array[columns][rows]来赋值和输出——columns是总列数、rows是总行数,这两个值远超出数组的合法索引范围(行索引合法区间是0~rows-1,列索引是0~columns-1)。越界访问属于C++中的未定义行为,程序可能看似正常,也可能直接崩溃,这就是你遇到随机异常的原因。

修正后的代码

#include <iostream> 

using namespace std;

void dynamicArray(int** array, int columns, int rows)
{
    cout << "i am working" << endl;

    for (int i = 0; i < rows; ++i)
    {
        for (int j = 0; j < columns; j++)
        {
            array[i][j] = 0; // 使用循环变量i(行索引)和j(列索引)访问元素
            cout << array[i][j] << "  " << flush;
        }
        cout << endl;
    }
}

int main() {

    int columns = 0;
    int rows = 0;
    cout << "state the number of rows: " << endl;
    cin >> rows;
    cout << "state the number of columns: " << endl;
    cin >> columns;

    int **array = new int*[rows];                   
    for(int i = 0; i < rows; ++i)
    {
        array[i] = new int[columns];
    }

    dynamicArray(array, columns, rows);

    // 释放动态分配的内存
    for(int l = 0; l < rows; l++)
        delete [] array[l];
    delete [] array;

    return 0;
}

更安全的替代方案(C++11及以上)

手动管理指针容易出现内存泄漏或越界问题,推荐使用vector<vector<int>>,它会自动处理内存分配和释放,还能直接初始化全0数组:

#include <iostream>
#include <vector>

using namespace std;

void dynamicArray(vector<vector<int>>& array)
{
    cout << "i am working" << endl;
    // 范围for循环遍历更简洁安全
    for (auto& row : array)
    {
        for (auto& elem : row)
        {
            elem = 0;
            cout << elem << "  " << flush;
        }
        cout << endl;
    }
}

int main() {
    int columns = 0;
    int rows = 0;
    cout << "state the number of rows: " << endl;
    cin >> rows;
    cout << "state the number of columns: " << endl;
    cin >> columns;

    // 直接创建rows行columns列、初始值全为0的二维vector
    vector<vector<int>> array(rows, vector<int>(columns, 0));

    dynamicArray(array);

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 00:15:39