Assigning Value to TArray

In my class header I declare the variable TArray TeamCount; Then in my cpp file I initialize the TArray using TeamCount.AddZeroed(NumTeams); Then I try to increment that value TeamCount[TestPlayerState->GetTeamNum()]++; I get the following error on TeamCount.AddZeroed(NumTeams);

Error	3	error C2662: 'int32 TArray<ElementType,FDefaultAllocator>::AddZeroed(int32)' : cannot convert 'this' pointer from 'const TArray<ElementType,FDefaultAllocator>' to 'TArray<ElementType,FDefaultAllocator> &'	

and then I get the following error on TeamCount[TestPlayerState->GetTeamNum()]++;

Error	4	error C3892: 'TArray<ElementType,FDefaultAllocator>::operator []' : you cannot assign to a variable that is const

I don’t know why this is happening, I am thinking i declared the variable wrong.

You sure you didn’t do const array?

Ya I triple checked, that is why I am so confused. It’s acting like it is const. I didn’t know if there were special rules for working with TArray

Might need to see some context on both TeamCount’s declaration, and the function in which it’s being accessed. My first guess is that if the this pointer is const at that point, all member vars will be as well. Maybe check the function signature?

void MyClass::DoSomething()
{
    TeamCount.AddZeroed(1); // Will work fine
}
void MyClass::DoSomething() const
{
    TeamCount.AddZeroed(1); // Compile error
}
1 Like

Yup that was the issue. Thanks for the help!