pointers - 奇怪的输出二维数组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
解决方案
由于您在创建数组后并未对其进行初始化,因此它可以具有任何值。
推荐阅读
- azure - 如何在 ARM 模板中组合复制和奇异属性
- ruby-on-rails - 带有嵌套资源的 Rails 表单的 NoMethodError
- php - 嵌套 For Each 循环中的回滚事务
- python - 使用python将现有文本转换为docx中的heading3格式
- python - SQLAlchemy:具有单表继承的邻接表
- sql - 如何在 SQL Server 中的多个列上应用字符串拆分功能
- ads - Google Ads 脚本和 Cookie
- angular - angular 11 ngmodel 未绑定到选择
- javascript - 如何在点击Highcharts Reactjs中的每一列时添加表格?
- wordpress - WP API 响应不显示我注册的元数据