0

I am trying to fix a Segmentation Fault error that occurs when I am running a C++ program which is caused by a structure I am calling to be too large. I am looking for a way to use my pre-existing C++ structure and move it from the stack to the heap.

My code looks like this:

n = 300;

struct arrayStruct {
   double arr[n][n];
};

int main(int argc, char *argv[]){

   arrayStruct temperature;
   // do a bunch of stuff including passing and receiving the arrayStruct within a few    functions
return 0

}

I have tried using malloc and new but only seem to get errors that I have no idea how to fix them. I've tried within in the structure as well as the main file but can't seem to get it working.

Thanks in advance

trincot
  • 317,000
  • 35
  • 244
  • 286
jeremy
  • 11
  • 1
  • 4
  • I cannot get it to apply to structures. If I was looking at a simple 2D array that is only defined in a function I would be good. The problem I have is getting it to a 2D array in a structure. – jeremy Feb 09 '13 at 03:50
  • Just allocate an instance of `arrayStruct` on the heap: `std::unique_ptr temperature(new arrayStruct());` – Charles Salvia Feb 09 '13 at 04:01

2 Answers2

0

Try use vector to create 2D array:

#include <vector>

 struct arrayStruct {
   arrayStruct()
   : arr(n, std::vector<double>(n))
   {
   }
   std::vector<std::vector<double>> arr;
};
billz
  • 44,644
  • 9
  • 83
  • 100
0

You can allocate an instance of arrayStruct on the heap:

std::unique_ptr<arrayStruct> temperature(new arrayStruct());
Charles Salvia
  • 52,325
  • 13
  • 128
  • 140
  • Ok so the problem with this implementation is that it doesn't seem to initiate the arr. I get the error: error: conversion from ‘std::unique_ptr >’ to non-scalar type ‘arrayStruct’ requested – jeremy Feb 09 '13 at 04:33