Search code examples
c++arrayspointersparameter-passingpass-by-value

Change array value from another class in C++


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;
 }

Solution

  • You are getting the error because H is null.

    The mistake is in the Heap::initialize(Element, int) method. You are assigning the local variable H of the Heap object you are calling the method in, instead of the object you are returning.

    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
    }
    

    Why are you creating a new Heap object and returning it? You can make the initialize method a void, like this:

    void Heap::initialize(int n) {
        H = new Element[n];
        capacity = n;
        size = 0;
    }
    

    Or if you need to return a new Heap object you can do it like this:

    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
    }
    

    Hope this was helpful.