DragonVet
DragonVet

Reputation: 409

Array of vtk type refuses to hold contents in C++

I'm using C++ to use vtk and when I hardcode vertices, my program works fine.
However, when I try to implement a for loop (to hold x-many vertices), the whole program crashes.
Here's the code I'm working with:

vtkIdType totalVertex[9];

for(int i = 0; i < sizeof(totalVertex); i++){
    totalVertex[i] = g->AddVertex();
}
// Hardcode example for syntax:
// vtkIdType v1 = g->AddVertex();

This would get 9 vertices and then I could manipulate them with commands such as

g->AddEdge (totalVertex[0], totalVertex[1]);

But my code never makes it to the place where edges are added, instead deciding to break in the loop.

I'm new to C++ so any ideas would be nice.

Upvotes: 0

Views: 156

Answers (1)

Matt Kline
Matt Kline

Reputation: 10497

This may not solve your issue, but there's a problem with

for(int i = 0; i < sizeof(totalVertex); i++)

and it may be related to the issue you're having.

sizeof in C++ yields size of whatever you provide in bytes, not the length of an array. Unless vtkIdType is one byte wide, you'll have errors. The "old-fahioned C way" to do this correctly would be

for(int i = 0; i < sizeof(totalVertex) / sizeof(totalVertex[0]); i++)

A cleaner, more modern C++ way would be

#include <array>

std::array<vtkIdType, 9> totalVertex;

for(int i = 0; i < totalVertex.size(); i++){
    totalVertex[i] = g->AddVertex();
}

Upvotes: 2

Related Questions