Reputation: 301
I'm getting an error with a piece of my code... In the following, "vertices" is defined as a vector of gVector3's, where gVector3 is a float array of length three (x,y,z coordinates of a point). The [] operator has been overloaded for the gVector3 class, so vertices[i][k] returns a float.
I have an error in this line: (*result)[i+k] = vertices[i][k]
. The full code as well as the error message is below. Any insights would be appreciated!
float* Polygon::getVertices(){
float* result = new float[vertices.size()*3];
for (int i = 0; i < vertices.size(); i++){
for (int k = 0; k < 3; k++){
(*result)[i+k] = vertices[i][k]; // invalid types for array subscript
}
}
return result;
}
Upvotes: 0
Views: 136
Reputation: 475
float* result = new float[vertices.size()*3];
is creating a pointer of float type. But in the nested for loop you tend to treat it as a pointer to array type hence the error. Either make the pointer an array type, or use *(result + 3*i + k) = vertices[i][k];
Upvotes: 0
Reputation: 781098
Since result
is declared as float*
, (*result)
is just a float
. It's not an array, so you can't subscript it. The assignment should be:
result[3*i + k] = vertices[i][k];
or:
*(result + 3*i + k) = vertices[i][k];
Notice that you also need to multiply i
by 3, otherwise you're going to repeatedly overwrite the same elements of result
. E.g. you'll write into result[1]
when i = 0, k = 1
and when i = 1, k = 0
. This is called row major indexing.
Upvotes: 1
Reputation: 1304
Try substituting result[3*i+k]
for (*result)[i+k]
. result
is a pointer to a float, not a pointer to a float array.
Upvotes: 0