Below is a simple markup of a program layout I can currently using. Its for OpenGL. Essentially I want to initialize the mesh before I ship it to the main loop. I can do this with
vector<Mesh> MeshContainer;
And once I initialize it, push it in the MeshContainer and then call it in the main loop like that. I would much rather be able to define a pointer in the Program struct, create the mesh in the init() function, and then store the pointer and then use the pointer.
#include <iostream>
#include <vector>
using std::vector;
using std::cout;
using std::endl;
struct Mesh {
vector<float> MeshVector;
};
struct Program {
bool shouldClose = false;
// Store the mesh as a pointer after we do some initialization.
Mesh *mp;
// Initialize is ran before the program and initializes before the loop begins.
void init() {
// Create the sudo-mesh.
Mesh myMesh;
// Give it some values. 9 in total.
myMesh.MeshVector = {
1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
};
mp = &myMesh;
}
// This is ran in the loop.
void run() {
cout << mp->MeshVector[0] << endl;
}
void loop() {
// Simulates layout of OpenGL application.
init();
// Program loop.
while (!shouldClose) {
// This simulates the draw loop.
run();
}
}
};
int main() {
// Create the program.
Program app;
app.loop();
return 0;
}
However, even in this simple application I wrote up, it gives me "vector subscript is out of range". Now it is pretty pointless (pun intended) to do this because I'll eventually write up a memory management class to bypass all this hoopla, but while I learn, I'd like this to be my quick and dirty solution.
What exactly am I doing wrong here? Should I be able to simply do:
cout << mp->MeshVector[0] << endl;
And get the result expected?
Edit:
My question does not involve a function returning a pointer. It simply looks to set a property of the struct to the pointer of some object I created in that method. Nothing is being returned.