我有一个变量,它是堆上的数组。我在堆上使用声明了此数组,并使用一个整数值乘以该对象的sizeOf值。我在代码中遇到麻烦,当我将对象设置为null时,用于为其创建空间的整数设置为0。
int numOfNodes;
int numOfEdges;
FILE *file;
file = fopen("input.txt", "r");
fscanf(file, "%d", &numOfNodes); //numOfNodes value is read in correct here
fscanf(file, "%d", &numOfEdges);//numOfEdges value is read in correct here
ELEMENT **T = (ELEMENT**) new ELEMENT()//setting space on the heap for an array of linked lists
for(int i=0; i<numOfNodes; i++){//This line is supposed to initialize all the Linked List inside the array to NULL. However on the second iteration the value for int numOfNodes changes to 0.
T[i]=NULL}
除了将numOfNodes用作数字以在堆上分配适当数量的空间外,不确定链接列表数组和int numOfNodes彼此之间没有任何关系。
编辑:使用new代替malloc,但仍然遇到相同的问题
答案 0 :(得分:-1)
int numOfNodes= 0; // good practice: always initialize
int numOfEdges= 0; // ditto
FILE* file= fopen("input.txt", "r"); // ditto
// you should check fscanf return value
fscanf(file, "%d", &numOfNodes); //numOfNodes value is read in correct here
fscanf(file, "%d", &numOfEdges); //numOfEdges value is read in correct here
您还应该检查这些数字是否> 0。
这很糟糕,请不要执行以下操作:
ELEMENT **T = (ELEMENT**) new ELEMENT()
您要的是一个元素的内存,
并且您获得的内存为ELEMENT*
。
通过强制强制转换为ELEMENT**
,您不仅
做错了什么,但告诉编译器“相信我,我知道我在做什么”。
作为C ++的一般规则,
如果您要铸造,那说明您做的不好。
通常有更好的方法。
而且不要使用旧风格的演员表,而是
reinterpret_cast, static_cast, dynamic_cast
和const_cast
。
如果您想要的是ELEMENT*
数组,
那么您应该要求它:
typedef ELEMENT* pElement;
ELEMENT** T= new pElement[numOfNodes]; // delete with delete[] T;
// or:
ELEMENT** T= malloc(sizeof(ELEMENT*) * numOfNodes); // delete with free(T);
现在您可以这样做:
for (int i= 0; i < numOfNodes; i++) {
// This line is supposed to initialize all the Linked List inside the array to NULL.
// However on the second iteration the value for int numOfNodes changes to 0.
T[i]= NULL; // nullptr on C++11
}
在现代C ++中,如果您这样做,我认为不需要for
ELEMENT** T= new pElement[numOfNodes]{}; // delete with delete[] T;
还可以使用auto
:
auto T= new pElement[numOfNodes]{};
请注意,您不仅要删除明确的演员表 还有隐式强制转换。
您也可以在C ++中使用
std::vector, which grows as needed
std::vector<ELEMENT*> T(numOfNodes, NULL);
将(numOfNodes,NULL)作为参数传递
分配初始化的numOfNodes元素
与NULL。
即使std::vector
处于堆栈中
元素的内存位于堆中。
您将以通常的方式访问它:
T[10]= new ELEMENT();
在现代C ++中,甚至更好:
std::vector<unique_ptr<ELEMENT> > T(numOfNodes);
将构造一个智能指针向量 只要您设置它们,就会调用删除 换成其他值
T[10].reset(new ELEMENT(1)); // will set the pointer to a new element initialized with 1
T[10].reset(new ELEMENT(2)); // will set the pointer to a another new element
以2初始化,并正确删除以1初始化的旧ELEMENT
T[10]->doSomething();
将照常工作。