Weird values on my vector - c++

I have a method who put some content on my vector, that work with no problem. After that I want to reuse the content on my vector in another part of the program, but the problem is the values are not he good. But I don't know where I miss something
Here is some part of the code
The class where I do the stuff
class MapGenerator
{
public:
void fillBoard(string level);
void renderBoard();
void initTileset();
MapGenerator();
~MapGenerator();
vector<Tile*> getTiles();
private:
char **board;
int w;
int h;
int tileW;
int tileH;
vector<Tile*> tiles;
};
It's on the initTileset I put some stuff on my tiles vector.
After that on another part of my programe I call renderBoard() And there is the problem, I already have the good number of element on my vector but the values are not the good...
Here is the method, maybe my way to itterate is not correct :
Where I put the content on vector
void MapGenerator::initTileset()
{
XMLDocument doc;
doc.LoadFile("ressources/xml/tiles.xml");
XMLElement* first = doc.FirstChildElement();
for (XMLElement* child = first->FirstChildElement("tile"); child != NULL; child = child->NextSiblingElement())
{
string texture = child->FirstChildElement( "texture")->GetText();
int x = atoi(child->FirstChildElement("x")->GetText());
int y = atoi(child->FirstChildElement("y")->GetText());
int w = atoi(child->FirstChildElement("w")->GetText());
int h = atoi(child->FirstChildElement("h")->GetText());
bool solid = false;
if (atoi(child->FirstChildElement("solid")->GetText() ) == 1)
solid =true;
char id = child->FirstChildElement("id")->GetText()[0];
cout << "ID " << id << endl;
cout << "create tile : w " << w << " h " << h << endl;
Tile tile(texture.c_str(), x, y, w, h, solid, id);
cout << "Tile ID " << tile.getId()<< endl;
this->tiles.push_back(&tile);
}
cout << tiles.size() << endl;
// renderBoard();
}
Where I try to reuse my vector
void MapGenerator::renderBoard()
{
SDL_Rect rect;
for (int i = 0; i < h; i++)
{
for (int j = 0;j < w; j++)
{
vector<Tile *>::iterator it;
for(it = tiles.begin(); it != tiles.end(); ++it) {
cout << " ID :" << (*it)->getId() << " h " <<(*it)->getRect().h << " w " << (*it)->getRect().w << endl;
if ((*it)->getId() == board[i][j])
{
rect.x = 32 * j;
rect.y = 32 * i;
rect.h = 32;
rect.w = 32;
SDL_RenderCopy( GameEngine::getInstance().getRenderer(), (*it)->getTexture(), NULL, &rect );
cout << " copy something y = " << i * 32<< " x = " << j *32<< " h " <<(*it)->getRect().h << " w " << (*it)->getRect().w <<endl;
}
}
}
cout << endl;
}
}
So someone have an idea ?

You have undefined behavior as you store pointers to a local variable in the vector. Once the for loop in the initTileset function iterates the tile variable goes out of scope and is destructed.
You need to allocate it on the heap:
Tile* tile = new Tile(texture.c_str(), x, y, w, h, solid, id);
You should of course not forget to free the allocated memory in the MapGenerator destructor.

Related

Shapes and their point ids. Shape ids are different but point ids are consecutively incremented

Requirement:
Shape ID: 0 (say rectangle)
Point IDs in rectangle: 0, 1, 2 and 3.
Shape ID: 1 (say square)
Point IDs in square: 0, 1, 2 and 3.
I wrote a code by for creating a shape and adding points to each shape. Classes Shape and LBP are defined.
Problem:
The point IDs are not starting from '0' in shape 1. Ideally, the point IDs in shape 1 (square )should start from 0 rather than 1. I feel that is the program appending the newly created point to the point set of the previous shape object i.e. shape 0 (rectangle).
Shape ID: 0 (say rectangle)
Point IDs: 0
Shape ID: 1 (say square)
Point IDs: 1
Question: How to make the point ids start from '0' for every new shape created?
The classes defined are as shown below.
MasterDefine.h
#include<iostream>
using namespace std;
class LBP
{
private:
double x, y;
int pointID;
static int pointCount;
public:
void setLBP(double, double);
void getLBP(double&, double&);
void addLBPatEnd();
void addLBPatLocation();
void delLBPatEnd();
void delLBPatLocation(int);
void setLBPID();
int getLBPID();
void goToNode(int);
int getNoOfPoints();
LBP(double, double);
~LBP();
LBP* next, * prev;
};
class Shape
{
private:
int shapeID;
static int shapeCount;
public:
void setShapeID();
int getShapeID();
LBP* points;
Shape();
};
Main.cpp
#include"MasterDefine.h"
int LBP::pointCount = 0;
int Shape::shapeCount = 0;
LBP* lbp, *firstPt, *lastPt;
void printLBPForward();
void printLBPReverse();
void delLBP(int);
void delAllLBPs();
int main()
{
cout << endl << "Hello world" << endl;
Shape* shape0 = new Shape;
cout << endl << "Shape id is " << shape0->getShapeID() << endl; //gives id of shape0
LBP* s0p0 = new LBP(22, 33); //point 0 of shape 0
shape0->points = s0p0;
Shape* shape1 = new Shape;
cout << endl << "Shape id is " << shape1->getShapeID() << endl; //gives id of shape1
LBP* s1p0 = new LBP(10, 5);//point 0 of shape 1
shape1->points = s1p0;
cout << endl << "point id is " << s1p0->getLBPID() << endl;
return 1;
}
LBP.cpp
#include"MasterDefine.h"
//#include "LBP.h"
LBP* lbpFirst, *lbpLast;
void LBP::getLBP(double& getX, double& getY)
{
getX = x;
getY = y;
}
void LBP::addLBPatEnd()
{
// cout << endl << "add lbp at end " << endl;
// cout << endl << "Pointer value in member function " << this << endl;
LBP* tempNode;
if (getNoOfPoints() == 1)
{
tempNode = this;
tempNode->next = NULL;
tempNode->prev = NULL;
lbpFirst = tempNode;
}
if (getNoOfPoints() == 2)
{
tempNode = this;
lbpFirst->next = tempNode;
lbpFirst->prev = tempNode;
tempNode->next = tempNode->prev = lbpFirst;
lbpLast = tempNode;
}
if (getNoOfPoints() > 2)
{
tempNode = this;
lbpLast->next = tempNode;
tempNode->next = lbpFirst;
lbpFirst->prev = tempNode;
tempNode->prev = lbpLast;
lbpLast = tempNode;
}
//goToNode();
}
void LBP::delLBPatEnd()
{
LBP* tempNodeDel;
tempNodeDel = lbpFirst;
do
{
tempNodeDel = tempNodeDel->next;
} while (tempNodeDel->getLBPID() != pointCount - 2);
cout << endl << "tempNodeDel id is " << tempNodeDel->getLBPID() << endl;
tempNodeDel->next = lbpFirst;
lbpFirst->prev = tempNodeDel;
}
void LBP::delLBPatLocation(int NodePos)
{
LBP* TempNodePosDel, *TempNodePosDelPrev, *TempNodePosDelNext;
TempNodePosDel = lbpFirst;
do
{
TempNodePosDel = TempNodePosDel->next;
} while (TempNodePosDel->getLBPID() != NodePos);
cout<<endl<<"NodeID that is to be deleted is "<<TempNodePosDel->getLBPID()<<endl;
cout << endl << "TempNodePosDel" << TempNodePosDel << endl;
TempNodePosDelPrev = TempNodePosDel->prev;
TempNodePosDelNext = TempNodePosDel->next;
cout << endl << "TempNodePosDelPrev id is " << TempNodePosDelPrev->getLBPID() << endl;
cout << endl << "TempNodePosDel id is " << TempNodePosDel->getLBPID() << endl;
cout << endl << "TempNodePosDelNext id is " << TempNodePosDelNext->getLBPID() << endl;
TempNodePosDelPrev->next = TempNodePosDelNext;
TempNodePosDelNext->prev = TempNodePosDelPrev;
cout << endl << "************************************" << endl;
cout << endl << "TempNodePosDelPrev " << TempNodePosDelPrev << endl;
cout << endl << "TempNodePosDelPrev->next " << TempNodePosDelPrev->next << endl;
cout << endl << "TempNodePosDelNext->prev " << TempNodePosDelNext->prev << endl;
cout << endl << "TempNodePosDelNext " << TempNodePosDelNext << endl;
cout << endl << "************************************" << endl;
}
void LBP::setLBPID()
{
pointID = pointCount;
}
int LBP::getLBPID()
{
return pointID;
}
void LBP::goToNode(int)
{
}
int LBP::getNoOfPoints()
{
return pointCount;
}
LBP::LBP(double setX, double setY)
{
x = setX;
y = setY;
setLBPID();
pointCount++;
addLBPatEnd();
}
LBP::~LBP()
{
cout << endl << "In destructor " << endl;
int NodePosForDel;
NodePosForDel = this->getLBPID();
if (NodePosForDel != 1)
{
delLBPatLocation(NodePosForDel);
}
/*delLBPatEnd();*/
cout << endl << "this pointer in destructor " << this << endl;
pointCount--;
}
Shape.cpp
#include"MasterDefine.h"
void Shape::setShapeID()
{
shapeID = shapeCount;
}
int Shape::getShapeID()
{
return shapeID;
}
Shape::Shape()
{
setShapeID();
shapeCount++;
}
Console output:
Shape id is 0
point id is 0
Shape id is 1
point id is 1
Can anyone help me in this? I am definitely missing something. I can't figure it out.
Question: How to make the point ids start from '0' for every new shape created?
Since your static int pointCount; member is static, it's the same member variable for all instances of class LBP, and because the instances share the member, upon creating a new instance, it has access to the changes made to this variable by all previous instances here:
LBP::LBP(double setX, double setY)
{
...
pointCount++;
...
}
This value is definitely not supposed to be stored statically, and it's neither responsibility of a vertex to store number of all vertices in a shape. Make a non-static variable of class Shape for example and keep that information there:
class Shape
{
private:
size_t verticesNum;
...

How to access array in function outside of main?

I am trying to create a program that prints out a store inventory. I print out the variables from my objects in the getInventory function. However, when I try and print out the entire inventory in the getStore function it returns nothing. I feel like it is an issue with my pointer properly pointing to my array but I am not sure.
#include <iostream>
#include <string>
class Weapon
{
private:
std::string nameWeapon, messageUsed;
bool ownedWeapon;
double weaponCost;
int numberUses;
public:
//Default constructor
Weapon()
{
nameWeapon = "weapon name";
messageUsed = "weapon sound";
weaponCost = 0;
ownedWeapon = false;
numberUses = 1;
}
//Non-Default Constructor
Weapon(std::string nW, std::string mU,double wC,bool oW, int nU )
{
nameWeapon = nW;
messageUsed = mU;
weaponCost = wC;
ownedWeapon = oW;
numberUses = nU;
}
void getInventory()
{
std::cout << nameWeapon << "\t" << messageUsed << "\t" << weaponCost << "\t" << ownedWeapon << "\t" << numberUses << "\n";
}
void getStore(Weapon* weaponArray)
{
std::cout << "Name" << "\t" << "Sound" << "\t" << "Price" << "\t" << "Owned";
for (int i = 0; i < 9; i++)
{
weaponArray[i].getInventory();
}
}
};
int main()
{
Weapon weaponArray[9]{};
weaponArray[0] = Weapon("Broad Sword","Clang!",50,false,3);
weaponArray[1] = Weapon("Champions Sword","Swoosh!",99.99,false,5);
weaponArray[2] = Weapon("Dagger","Ding!",12.25,false,1);
weaponArray[3] = Weapon("Poisin Dagger","Shh",18.50,false,1);
weaponArray[4] = Weapon("Sturdy Dagger","Gronk!",14.75,false,3);
weaponArray[5] = Weapon("Short Bow","T'wang!",35.75,false,3);
weaponArray[6] = Weapon("Champions Bow","Swoop!",90.15,false,5);
weaponArray[7] = Weapon("Champions Axe","Bash!",110.11,false,6);
weaponArray[8] = Weapon("Throwing Axe","Bonk!",25.75,false,2);
void getStore();
system("pause");
return 0;
}
void getStore();
This is a function stub. It declares a function getStore that takes no arguments and returns nothing to be implemented later. This is almost definitely a typo.
Further, because void getStore(Weapon* weaponArray) is in the Weapon class, you have to call it on a weapon, which doesn't look right. You probably mean to do this:
class Weapon {
// ...
};
void getStore(Weapon* weaponArray, unsigned sz)
{
std::cout << "Name" << "\t" << "Sound" << "\t" << "Price" << "\t" << "Owned";
for (unsigned i = 0; i < sz; i++)
{
weaponArray[i].getInventory();
}
}
int main()
{
Weapon weaponArray[9]{};
weaponArray[0] = Weapon("Broad Sword","Clang!",50,false,3);
//...
getStore(weaponArray, 9);
}

Array data is 'lost' after passing the array to another object

I'm having a problem where the objects in my array are lost when I pass the array through a constructor. My first guess was that I needed to change it to an array of pointers but that resulted in a segfault. My next guess was that I needed to copy the array data after passing it but that also didn't work. Here's the problem code:
Universe Object:
class Universe {
public:
Star stars[]; int starsLength;
Planet planets[]; int planetsLength;
public:
Universe(Star st[], int stl, Planet pl[], int pll) {
stars < st; starsLength = stl;
planets < pl; planetsLength = pll;
}
Universe() {
}
public:
void render() {
for(int i = 0;i < starsLength;i++) {
//std::cout << "STAR: " << stars[i].location.x << "," << stars[i].location.y << " " << stars[i].size << " " << stars[i].color.r << "," << stars[i].color.g << "," << stars[i].color.b << "\n";
renderCircle(stars[i].location, stars[i].size, stars[i].color);
}
for(int i = 0;i < planetsLength;i++) {
renderCircle(planets[i].location, planets[i].size, planets[i].color);
}
}
void renderCircle(Point location, float size, Color color) {
glBegin(GL_LINES);
glColor3f(color.r,color.g,color.b);
glVertex2f(location.x+size, location.y+size);
glVertex2f(location.x-size, location.y-size);
glVertex2f(location.x-size, location.y+size);
glVertex2f(location.x+size, location.y-size);
glEnd();
}
};
Method that creates the Universe and gives it the array:
Universe buildUniverse(int size, int seed) {
Point bounds = Point{static_cast <float> (size),static_cast <float> (size)}; //0,0 to size,size
int starCount = min(size/10,random(size/5));
int planetCount = min(size/3,random(size));
Star stars[starCount];
Planet planets[planetCount];
//std::cout << "-- Created " << starCount << " stars and " << planetCount << " planets...\n";
for(int i = 0;i < starCount;i++) {
Point location = {random(bounds.x),random(bounds.y)};
Point velocity = {random(bounds.x/100.0f),random(bounds.y/100.0f)};
float size = random(bounds.x/100.0f);
float mass = random(size*(random(1.0f)+0.5f));
Color color = {1.0f,1.0f,1.0f};
stars[i].setStar(location,velocity,size,mass,color);
}
for(int i = 0;i < planetCount;i++) {
Point location = {random(bounds.x),random(bounds.y)};
Point velocity = {random(bounds.x/100.0f),random(bounds.y/100.0f)};
float size = random(bounds.x/100.0f);
float mass = random(size*(random(1.0f)+0.5f));
Color color = {random(1.0f),random(1.0f),random(1.0f)};
planets[i].setPlanet(location,velocity,size,mass,color);
}
Universe uni = {stars, starCount, planets, planetCount};
std::cout << "Star in array: " << stars[0].location.x << "," << stars[0].location.y << " " << stars[0].size << " " << stars[0].color.r << "," << stars[0].color.g << "," << stars[0].color.b << "\n";
std::cout << "Star passed to uni in an array: " << uni.stars[0].location.x << "," << uni.stars[0].location.y << " " << uni.stars[0].size << " " << uni.stars[0].color.r << "," << uni.stars[0].color.g << "," << uni.stars[0].color.b << "\n";
return uni;
}
Output of of the program:
Building universe...
Star in array: 39.922,39.155 0.167611 1,1,8.85715e-39
Star passed to uni in an array: 7.00649e-45,2.24208e-44 0.0282954 5.90446e-39,1.4013e-45,1.4013e-45
Initializing threaded renderer...
Starting simulation...
What am I doing wrong?
First, your code is not valid C++. Declaring empty arrays using [] does not exist in C++.
So the first thing is to turn this into valid C++ that still preserves what you're trying to accomplish. One solution is to use std::vector:
#include <vector>
class Universe {
public:
std::vector<Star> stars;
std::vector<Planet> planets;
public:
Universe(const std::vector<Star>& st,
const std::vector<Planet>& pl) : stars(st), planets(pl) {}
};
Note the replacement of the non-C++ code with std::vector. Also note that we initialize the vectors using the initializer-list.
Last, note that we no longer need to keep the sizes as separate member variables. Why? Because a vector knows its size by calling the vector::size() member function. For example:
for(int i = 0;i < starsLength;i++) {
can be replaced with
for(int i = 0;i < stars.size();i++) {
In your buildUniverse function, use the following changes:
Universe buildUniverse(int size, int seed) {
Point bounds = Point{static_cast <float> (size),static_cast <float> (size)}; //0,0 to size,size
int starCount = min(size/10,random(size/5));
int planetCount = min(size/3,random(size));
std::vector<Star> stars(starCount);
std::vector<Planet> planets(planetCount);
//...
Universe uni(stars, planets);
The rest of the code stays the same. Now, if after the call to create the Universe, you see that the vectors didn't pass the correct information, then look further. The code above conforms to "normal" C++, such that we can go further and figure out the issue.

Something to change

as the title, i don't know how to convert this struct into a class?
Also i've another problem, how can i convert the array Sets[][] and top[] into vector?
I tried, but i have problem with editing in a vector of [i] position.
//*******************************
// Class Kruskal *
//*******************************
class kruskal
{
private:
struct Edge {
//Arco: vertice V -> vertice U : peso W
int v, u, w;
Edge(int v, int u, int w) : v(v), u(u), w(w) {}
bool operator < (const Edge& c) const{
if (w != c.w)
return w < c.w;
if (v != c.v)
return v < c.v;
return u < c.u;
}
};
int n; //n. nodes
int nre; //n. edges
vector<Edge> edges; //vector contenente tutti gli archiì
vector<Edge> tree; //Albero che conterrà tutti gli archi dell'MST
int sets[100][10]; //matrice contente i sets (tagli)
int top[100]; //supporto alla matrice dei sets
public:
kruskal(){};
~kruskal(){ cout << "Grafo distrutto"; };
void read_graph();
void sort_edges();
void algorithm();
int find_node(int);
void print_min_span_t();
};
//*******************************************
// read_graph() *
// Legge in input n, nre, e i vari archi *
//*******************************************
void kruskal::read_graph()
{
cout << "Algoritmo di Kruskal" << endl;
cout << "Minimum Spanning Tree su Grafo non orientato e pesato" << endl << endl;
cout << "-Inserire numero di nodi e numero di archi: ";
cin >> n >> nre;
int v, u, w;
cout << "-Inserire vertice 1, vertice 2 e peso:" << endl;
for (int i = 0; i < nre; i++)
{
cin >> v >> u >> w;
if (w != 0)
{
edges.push_back(Edge(v, u, w));
}
}
//Print graph edges
cout << endl << endl << "Archi del grafo:" << endl;
for (unsigned int i = 0; i < edges.size(); i++)
{
cout << " < " << edges[i].v
<< " , " << edges[i].u
<< " > " << edges[i].w << endl;
}
}
//*******************************************
// sort_edges() *
// Ordina gli archi per peso con sort() *
//*******************************************
void kruskal::sort_edges()
{
sort(edges.begin(), edges.end());
//Print graph edges
cout << endl << endl << "Archi del grafo dopo l'ordinamento:" << endl;
for (unsigned int i = 0; i < edges.size(); i++)
{
cout << " < " << edges[i].v
<< " , " << edges[i].u
<< " > " << edges[i].w << endl;
}
}
//***********************************************
// algorithm() *
// Inizializza i sets (make-set) *
// Trova i sets dei due nodi (Find_node) *
// Controlla se i sets sono diversi (Findset) *
// Se si lo inserisce nel vector "tree" (MST) *
// E unisce i due sets (Union) *
// Altrimenti "scarta" l'arco *
//***********************************************
void kruskal::algorithm()
{
//Make-set
for (int i = 1; i <= n; i++)
{
sets[i][1] = i;
top[i] = 1;
}
cout << endl << "Avvio algoritmo di Kruskal:" << endl << endl;
for (unsigned int i = 0; i < edges.size(); i++)
{
int p1 = find_node(edges[i].v);
int p2 = find_node(edges[i].u);
//Findset(p1) != Findset(p2)
if (p1 != p2)
{
cout << "Arco preso nell'albero:"
<< " < " << edges[i].v << " , "
<< edges[i].u << " > " << endl << endl;
//Union
tree.push_back(Edge(edges[i].v, edges[i].u, edges[i].w));
//Union two sets
for (int j = 1; j <= top[p2]; j++)
{
top[p1]++;
sets[p1][top[p1]] = sets[p2][j];
}
top[p2] = 0;
}
else
{
cout << "Questo arco"
<< " < " << edges[i].v << " , "
<< edges[i].u << " > " << "forma un ciclo ed e' stato rimosso" << endl << endl;
}
}
}
//*******************************************
// find_node() *
// Trova il sets di appartenenza del nodo *
//*******************************************
int kruskal::find_node(int n)
{
for (int i = 1; i <= nre; i++)
{
for (int j = 1; j <= top[i]; j++)
{
if (n == sets[i][j])
return i;
}
}
return -1;
}
//*******************************
// print_min_span_t() *
//*******************************
void kruskal::print_min_span_t()
{
cout << endl << "Minimum Spanning Tree del grafo:" << endl;
for (unsigned int i = 0; i < tree.size(); i++)
{
cout << " < " << tree[i].v
<< " , " << tree[i].u
<< " > " << tree[i].w << endl;
}
}
As top is just the size of corresponding sets, you may remove top, and change std::vector<std::vector<int> > sets.
Then
MakeSet:
//Make-set
sets.resize(nre); // or n, not sure of the definition of each one...
for (std::size_t i = 0; i != nre; ++i)
{
sets[i].push_back(i);
}
UnionSet:
//Union two sets
sets[p1].insert(sets[p1].end(), sets[p2].begin(), sets[p2].end());
sets[p2].clear();
Find node:
int kruskal::find_node(int n) const
{
for (size_t i = 0; i != sets.size(); ++i)
{
if (std::find(sets[i].begin(), sets[i].end(), n) != sets[i].end())
{
return i;
}
}
return -1;
}

EXC_BAD_ACCESS at main method declaration

I'm trying to get some old C++ code up and running. I've gotten it to compile without error, but it immediately segfaults when I run, without entering main. When I use gdb to find out where things are going wrong, I find the following:
(gdb) run
Starting program: /Users/dreens/Documents/OH/extrabuncher2/ParaOHSB
Reading symbols for shared libraries +++. done
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x00007fff5636581c
0x000000010000151e in main (argc=1, argv=0x100000ad0) at ParaMainOHSlowerBuncher.cc:13
13 int main(int argc, char *argv[]){
(gdb) backtrace
#0 0x000000010000151e in main (argc=1, argv=0x100000ad0) at ParaMainOHSlowerBuncher.cc:13
(gdb)
Does anyone know what could cause a memory access issue right at the start of the main method?
The code is rather large, but here is the file containing the main method. Could the included .hh and .cc files be a part of the problem? Should I attach them?
Thanks!
David
#include <iostream>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include "MoleculeEnsemble.hh"
#include "SlowerForceLoadOH32.cc"
#include "SlowerForceLoadOH12.cc"
//#include "SlowerForceLoad3mmBuncher.cc"
#include "SlowerForceLoad4mmBuncher.cc"
using namespace std;
int main(int argc, char *argv[]){
//int main(){
cout << "Ahhhh!" << endl;
/******Parallel Crap********/
/*
int totalnodes = 0;
int mynode = 0;
MPI_Status status;
MPI_Init(&argv,&argc);
MPI_Comm_size(MPI_COMM_WORLD,&totalnodes);
MPI_Comm_rank(MPI_COMM_WORLD,&mynode);
srand(time(NULL)*mynode);
*/
/******Distribution Parameters *******/
long MoleculeNumber = long(5e4);
double Xcenter = 0;
double Ycenter = 0;
double Zcenter = 0;
double DeltaX = 0.0015;
double DeltaY = 0.0015;
double DeltaZ = 0.01;
int FlatX = 1;
int FlatY = 1;
int FlatZ = 1;
double vXcenter = 0;
double vYcenter = 0;
double vZcenter = 406;
double Vcalc = 406;
double vZfinal = 0;
double DeltavX = 2;
double DeltavY = DeltavX;
double DeltavZ = 40;
int FlatvX = 0;
int FlatvY = 0;
int FlatvZ = 0;
int TimeArrayOnly = 0; //Outputs only Time Array
double TimeOffset = 0; //Adds valve-skimmer flight time to ToF array
/*******Overtone Parameters********/
int S = 1; //parameter S=Vz/Vswitch as defined by VDM et al.
int JILAOT = 0; //JILAOT is either 0 or 1, denoting whether or not to use special switching
/*******Hexapole Parameters********/
double VSD = 0.06;
double Voltage = 2000;
double HexRadius = .00268;
double HexStart = .0238;
double HexEnd = .083170;//0.089103;
double HexOn = 1e-6;
double HexOff = 203e-6;//224e-6; 212 for current data; Good = 243e-6 for 408m/s
double DeltaT = 1e-6;
double DeltaTSeqGen = 1e-9; //Need to use smaller time steps for finding the time sequence
double DetectionTime = HexOff; //Use to fake out hex code
double TriggerLatency = 0;//170e-9;
/*******Detection Parameters*******/
double DetectionPosition = double(0.9319);//0.257480; <- for viewing at 31.5 ||||| 0.9428; <-Mag trap(4stages), .9319 <-MagTrap(3Stages)
double IrisWidth = 0.008;//31.5 0.0023 //PostSlower.015;
double LaserRadius = .001;
/*****Bunching Paramaters******/
int BunchNumber = 0;
int NumberUsed = 0;
/*****Timing Variables*********/
time_t start, finish;
time( &start);
/*****Molecule Parameters******/
double mass =double(17*1.672e-27);
/******ToF Detection Arrays and Slowing Parameters *********/
double Phi = double(34.2);
double PhiEB = double(0);
int NumberOfStages = int(142/S); //Use 142 for Big machine
int EBStages = 3; //Larger Add-on stages at end of slower
double BuncherScale = 1;
double Time[int(1e7)];
int ToFSignal32[int(1e7)];
int ToFSignal12[int(1e7)];
double TimeArray[800];
double VExit[800];
double Average32[7];
double Average12[7];
int LOST[200];
/*************Finished ToF Detection Arrays and Slowing Parameters ********/
/******Force Arrays********/
int Xnumber = 111;
int Ynumber = 21;
int Znumber = 21;
int FLength = Xnumber*Ynumber*Znumber;
double AXxDT[FLength];
double AYxDT[FLength];
double AZxDT[FLength];
double AZxDTSeqGen[FLength];
SlowerForceLoadOH32(AZxDT, AYxDT, AXxDT); //Note how Z and X are placed in this function. My matlab code calls the longitudnal dimension X, here it is Z
double DTovermass = DeltaT/mass;
for(int j = 0; j <FLength; j++){
AXxDT[j] = DTovermass*AXxDT[j];
AYxDT[j] = DTovermass*AYxDT[j];
AZxDT[j] = DTovermass*AZxDT[j];
AZxDTSeqGen[j] = DeltaTSeqGen*AZxDT[j]/DeltaT;
}
double AXxDT12[FLength];
double AYxDT12[FLength];
double AZxDT12[FLength];
SlowerForceLoadOH12(AZxDT12, AYxDT12, AXxDT12); //Note how Z and X are placed in this function. My matlab code calls the longitudnal dimension X, here it is Z
for(int j = 0; j <FLength; j++){
AXxDT12[j] = DTovermass*AXxDT12[j];
AYxDT12[j] = DTovermass*AYxDT12[j];
AZxDT12[j] = DTovermass*AZxDT12[j];
}
/********Load Extra Buncher Forces*********/
int XnumberEB = 251;
int YnumberEB = 41;
int ZnumberEB = 41;
int FLengthEB = XnumberEB*YnumberEB*ZnumberEB;
double AXxDTEB[FLengthEB], AYxDTEB[FLengthEB], AZxDTEB[FLengthEB], AZxDTSeqGenEB[FLengthEB];
SlowerForceLoad4mmBuncher(AZxDTEB, AYxDTEB, AXxDTEB);
for(int j = 0; j <FLengthEB; j++)
{
AXxDTEB[j] = DTovermass*AXxDTEB[j]/BuncherScale;
AYxDTEB[j] = DTovermass*AYxDTEB[j]/BuncherScale;
AZxDTEB[j] = DTovermass*AZxDTEB[j]/BuncherScale;
AZxDTSeqGenEB[j] = DeltaTSeqGen*AZxDTEB[j]/(DeltaT*BuncherScale);
}
/********* End All initiliazation ***************************/
/************Beginning Calculation *************************/
//Create Molecule Ensemble
MoleculeEnsemble Alice(MoleculeNumber,Xcenter,Ycenter,Zcenter,DeltaX,DeltaY,DeltaZ,FlatX,FlatY,FlatZ,vXcenter,vYcenter,vZcenter,DeltavX,DeltavY,DeltavZ,FlatvX,FlatvY,FlatvZ);
//MoleculeEnsemble Bob(MoleculeNumber,Xcenter,Ycenter,Zcenter,DeltaX,DeltaY,DeltaZ,FlatX,FlatY,FlatZ,vXcenter,vYcenter,vZcenter,DeltavX,DeltavY,DeltavZ,FlatvX,FlatvY,FlatvZ);
//Generate the Timing Sequence
Alice.TimeArrayGeneratorWithBuncher(Vcalc,Phi,PhiEB,TimeArray,VExit,AZxDTSeqGen,AZxDTSeqGenEB,HexOff,DeltaTSeqGen,BunchNumber,vZfinal,NumberUsed,NumberOfStages,S,EBStages);
/*if(mynode == 0){
cout << "Slowing utilized " << NumberUsed << " stages, yielding a final velocity of " << VExit[NumberUsed] << " m/s." << endl;
cout << endl;
for(int kk = 0; kk < NumberOfStages; kk++){cout << kk << " , " << TimeArray[kk] << " , " << VExit[kk] << endl;}
}*/
/*Alice.MoleculeEnsemble_Averager(Average32);
Bob.MoleculeEnsemble_Averager(Average12);
cout << "Processor: " << mynode << "\t" << sqrt(pow(Average32[3],2)+pow(Average32[4],2)) << ", " << sqrt(pow(Average12[3],2)+pow(Average12[4],2));
cout << " Mean = " << Average32[6] << ", " << Average12[6] << endl << endl << endl;
*/
if(TimeArrayOnly!=1)
{
//Fly the Ensemble through the hexapole
Alice.HexapoleFlightOH(Voltage, HexRadius, HexStart, HexEnd, HexOn, HexOff, DeltaT, double(3/2), DetectionTime);
//Bob.HexapoleFlightOH(Voltage, HexRadius, HexStart, HexEnd, HexOn, HexOff, DeltaT, double(1/2), DetectionTime);
/*
Alice.MoleculeEnsemble_Averager(Average32);
Bob.MoleculeEnsemble_Averager(Average12);
cout << "Processor: " << mynode << "\t" << sqrt(pow(Average32[3],2)+pow(Average32[4],2)) << ", " << sqrt(pow(Average12[3],2)+pow(Average12[4],2));
cout << " Mean = " << Average32[6] << ", " << Average12[6] << endl << endl << endl;
*/
//Fly the Ensemble through the slower
Alice.SlowerFlight(LOST, Time, ToFSignal32, Phi, TimeArray, DeltaT, AXxDT, AYxDT, AZxDT, AXxDTEB, AYxDTEB, AZxDTEB, Xnumber, Ynumber, Znumber, DetectionPosition, IrisWidth, LaserRadius, NumberOfStages, EBStages,S, TriggerLatency);
//Bob.SlowerFlight(LOST, Time, ToFSignal12, Phi, TimeArray, DeltaT, AXxDT12, AYxDT12, AZxDT12, Xnumber, Ynumber, Znumber, DetectionPosition, IrisWidth, LaserRadius, NumberOfStages, EBStages, S, TriggerLatency);
}
/**********Ending Calculation **********************/
//Alice.MoleculeEnsemble_Drawer();
/*
Alice.MoleculeEnsemble_Averager(Average32);
Bob.MoleculeEnsemble_Averager(Average12);
cout << "Processor: " << mynode << "\t" << sqrt(pow(Average32[3],2)+pow(Average32[4],2)) << ", " << sqrt(pow(Average12[3],2)+pow(Average12[4],2));
cout << " Mean = " << Average32[6] << ", " << Average12[6] << endl << endl;
*/
//Output ToF signal
if(TimeArrayOnly!=1)
{
for(int ii = 0; ii < int(1e7); ii++)
{
if(ToFSignal32[ii] > 0 && Time[ii] > 3e-3)
{
cout << Time[ii]+TimeOffset << "," << ToFSignal32[ii] << endl;
//+double(VSD/vZcenter)+38e-6 << "," << ToFSignal32[ii] << endl;
}
if(ToFSignal12[ii] > 0 && Time[ii] > 3e-3)
{
cout << Time[ii]+TimeOffset << "," << ToFSignal12[ii] << endl;
//+double(VSD/vZcenter)+38e-6 << "," << ToFSignal12[ii] << endl;
}
}
}
if(TimeArrayOnly==1)
{
for(int ii = 0; ii < NumberOfStages+EBStages+1; ii++)
{
cout << ii << "\t" << TimeArray[ii] << "\t" << VExit[ii] << endl;
//+double(VSD/vZcenter)+double(265e-6) << "\t" << VExit[ii] << endl;
}
}
/*for(int ii = 0; ii < NumberOfStages; ii++)
{
cout << ii << "\t" << LOST[ii] << endl;
}
*/
/*
MPI_Finalize();
*/
}
You're out of stack space.
You declare very large arrays in your code (over 10 million elements), which are all allocated on the stack. Instead of declaring the arrays statically, use dynamic memory allocation. So, instead of
double Time[int(1e7)];
write
double* Time;
Time = new double[int(1e7)];
and hope to have enough RAM in your computer :)