Reputation: 81
I have a problem with my function. I can't seem to make it return an array of a struct.
Here is the MyApp.h header file:
struct Vertex
{
glm::vec3 p;
glm::vec3 c;
};
class CMyApp
{
public:
CMyApp(void);
~CMyApp(void);
Vertex[] DrawCircle(int cx, int cy);
...
It underlines the DrawCircle and "expects a ';'".
Here is the MyApp.cpp (Of course, header included):
Vertex[] CMyApp::DrawCircle(int cx, int cy) {
Vertex result[42];
result[0] = { glm::vec3((float)cx, (float)cy, 0.0), glm::normalize(glm::vec3(0, 0, 1)) };
for (int ii = 1; ii < 21; ii++) {
float theta = 2.0f * 3.1415926f * float(ii) / float(20);
float x = 0.5 * cosf(theta);
float y = 0.5 * sinf(theta);
result[ii].p = glm::vec3(x, y, 0.0);
result[ii].c = glm::normalize(result[ii].p);
}
result[21] = { glm::vec3((float)cx, (float)cy, 2.0), glm::normalize(glm::vec3(0, 0, 1.0)) };
for (int ii = 22; ii < 42; ii++) {
float theta = 2.0f * 3.1415926f * float(ii) / float(20);
float x = 0.5 * cosf(theta);
float y = 0.5 * sinf(theta);
result[ii].p = glm::vec3(x, y, 2.0);
result[ii].c = glm::normalize(result[ii].p);
}
return result;
}
Same underline here under the function name's DrawCircle for expected ";".
If I remove the array marks then the only error is the return statement. I want to return as an array tho.
Thanks for help in advance.
Upvotes: 0
Views: 323
Reputation: 162164
I want to return as an array tho.
You can't. C and C++ don't allow it. What you can do in C++ is returning a std::vector
which you should use instead of plain arrays anyway.
Upvotes: 0
Reputation: 1635
You cannot return a local array. Such an array is allocated on the stack; when the function returns, all its content is available for other stack variables. If you use it after the call, its content is likely to be corrupted.
So
Vertex[] CMyApp::DrawCircle(int cx, int cy) {
Vertex result[42];
return result;
}
is undefined behavior for the compiler.
You should use a vector instead. Its move constructor makes it efficient for returning many results organized as an array.
std::vector<Vertex> CMyApp::DrawCircle(int cx, int cy) {
std::vector<Vertex> result;
result.reserve(42);
// same content than your original code.
...
return result;
}
Note that if you declare
class CMyApp
{
public:
CMyApp(void);
~CMyApp(void);
typedef Vertex ArrayOfVertices[];
ArrayOfVertices DrawCircle(int cx, int cy);
};
You obtain the error message:
error: ‘DrawCircle’ declared as function returning an array
ArrayOfVertices DrawCircle(int cx, int cy);
Upvotes: 3