The error "Object reference not set to an instance of an object" usually means that you are trying to access an object that has not been initialized yet. In your case, the labels array is declared as a static variable, but it has not been initialized to a specific size.
To fix the error, you need to initialize the labels array with a specific size before using it in the IniciarLabels() function. One way to do this is to create a new array with the desired size and assign it to the labels variable, like this:
static array<Label^>^ labels = gcnew array<Label^>(MAX_LABELS);
Where MAX_LABELS is a constant that defines the maximum number of labels that you expect to use in your program.
Alternatively, if you don't know the size of the array in advance, you can use a List instead of an array, like this:
static List<Label^>^ labels = gcnew List<Label^>();
Then, in your IniciarLabels() function, you can add labels to the list using the Add method:
void IniciarLabels()
{
tam = palavra->Length;
for (int i = 0; i < tam; i++)
{
Label^ label = gcnew Label();
label->Font = gcnew System::Drawing::Font("Arial", 26, FontStyle::Bold);
label->ForeColor = Color::Black;
label->TextAlign = ContentAlignment::MiddleLeft;
label->AutoSize = false;
label->Size = System::Drawing::Size(40, 40);
label->Text = palavra[i] == ' ' ? " " : "_";
label->Location = i == 0 ? System::Drawing::Point(X, Y + 5) : System::Drawing::Point((labels[i - 1]->Location.X + 43), Y + 5);
panel1->Controls->Add(label);
labels->Add(label);
}
}
This way, you can add labels to the list dynamically without having to worry about the size of the array.