I'm getting Segmentation Fault error. I'm fairly new to C++ so not really familiar with pointers and other such things. This seems to be a fundamental aspect but i can't seem to figure it out, I've spent countless hours on it.
I have 5 files element.h, element.cpp, heap.h, heap.cpp, main.cpp
error occurs on the line
h.setElements(e,i);
Which is a function in Heap.cpp
I know it has something to do with arrays
MAIN.CPP
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include "heap.h"
#include "element.h"
using namespace std;
int main(){
Heap h;
h = h.initialize(3);
for(int i=0;i<h.getCapacity(); ++i){
Element e;
e.setKey(i);
h.setElements(e,i); // Error occurs here
}
h.printHeap(h);
return 0;
}
HEAP.H
#ifndef heap_h
#define heap_h
#include "element.h"
#include <iostream>
using namespace std;
class Heap {
public:
Element* getElements();
void setElements(Element e,int index);
Heap initialize(int n);
void printHeap(Heap heap);
private:
int capacity;
int size;
Element* H;
};
#endif
HEAP.CPP
#include "heap.h"
Heap Heap::initialize(int n){
H = new Element[n];
Heap h;
h.capacity = n;
h.size = 0;
return h;
}
void Heap::printHeap(Heap heap){
for(int i=0;i<heap.capacity;++i){
cout << "Element " << i << " = " << H[i].getKey() << endl;
}
}
void Heap::setCapacity(int nCapacity ) {
capacity = nCapacity;
}
int Heap::getCapacity(void) {
return capacity;
}
void Heap::setSize(int nSize ) {
size = nSize;
}
int Heap::getSize(void) {
return size;
}
Element* Heap::getElements(void){
return H;
}
void Heap::setElements(Element e,int index){
H[index] = e;
}
答案 0 :(得分:2)
您收到错误,因为H为空。
错误在于Heap :: initialize(Element,int)方法。 您正在分配要调用方法的Heap对象的局部变量H,而不是您要返回的对象。
Heap Heap::initialize(int n){
H = new Element[n]; // You are assigning H for the current heap object
Heap h; // Here you are creating a new Heap object
h.capacity = n;
h.size = 0;
return h; // You haven't assigned h.H
}
为什么要创建一个新的Heap对象并将其返回? 您可以将initialize方法设为void,如下所示:
void Heap::initialize(int n) {
H = new Element[n];
capacity = n;
size = 0;
}
或者如果你需要返回一个新的Heap对象,你可以这样做:
Heap Heap::initialize(int n) {
Heap h;
h.H = new Element[n];
h.capacity = n;
h.size = 0;
return h; // You have assigned h.H
}
希望这有用。