首页 > 解决方案 > 奇怪的输出二维数组c ++

问题描述

您好我正在尝试使用构造函数初始化二维数组。但是当输入的大小为 9 或 10 时,结果数组的成员总是 48(总是位于 graph[0][9])。其他大小,即 12、13、...、20,不要没有这个问题。请告诉我出了什么问题。非常感谢!

我是否需要为每个成员分配值,这与内存有关?

#include <iostream>

class Graph {
public:
    Graph(int s=10);
    void print_graph() const;
private:
    int **graph;
    int size;
};

// function to create a 2D array
Graph::Graph(int s)
{
    size = s;
    
    graph = new int* [size];
    for (int i = 0; i < size; i++) 
        graph[i] = new int [size];
}

void Graph::print_graph() const
{
    for (int i = 0; i < size; i++) 
    {
        for (int j = 0; j < size; j++)
            std::cout << graph[i][j] << " ";
        std::cout << std::endl;
    }
}


int main()
{
    Graph g(9);
    g.print_graph();
}

输出:

0 0 0 0 0 0 0 0 48

0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0 0

标签: pointers

解决方案


运算符 new 将内存初始化为零

由于您在创建数组后并未对其进行初始化,因此它可以具有任何值。


推荐阅读