[英]How to dynamically create an array of pointers?
I am trying to dynamically create an array of size 'n' that can contain pointers to multiple adjacency lists. 我正在尝试动态创建大小为'n'的数组,该数组可以包含指向多个邻接表的指针。 However when I run my code, it doesn't result in an array of nodes, it just results in this: 但是,当我运行代码时,它不会导致节点数组,而只会导致以下结果:
It's not an array, it's just a single node. 它不是数组,而只是一个节点。
Here's my code: 这是我的代码:
main.cpp main.cpp中
#include "graph.h"
using namespace std;
int main() {
graph g;
return 0;
}
graph.cpp graph.cpp
#include "graph.h"
// Constructor
graph::graph()
{
int size = 5; //
// Allocate array of size (n) and fill each with null
adjListArray = new node*[size];
// Set each entry in array to NULL
for (int i = 0; i < size; i++)
{
adjListArray[i] = NULL;
}
}
graph.h graph.h
#include<cassert>
#include<iostream>
#include<string>
#include<fstream>
using namespace std;
struct node
{
int name;
node *next;
};
class graph
{
public:
// Constructors/destructors
graph();
~graph();
private:
node** adjListArray; // Array of pointers to each adjacency list
};
Where am I going wrong? 我要去哪里错了?
问题是,当您只有一个指向内存开始的指针时,无法得知内存有多大,因此您的IDE仅假设它的大小为sizeof(datatype)
并且仅向您显示第一个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.