Access violation error when I try to access my the TeamScore array in GameState in HUD

My goal here is to set a HUD object to show a team score. I can access my GameState class but when I try to get a value from my TArray TeamScores the editor crashes and gives me “Access Violation - code c0000005 (first/second chance not available)”. TeamScores is public in the GameState header. I’m using version 4.4.3. This is the code in the HUD that is causing the crash or at least what the crash report is pointing too, which is the second line.

AFPSGameState* GS = Cast<AFPSGameState>(GetWorld()->GameState);
const int32 VirusScore = GS->TeamScores[0];

Does anybody know why it is crashing?

You need to test that the AFPSGameState pointer is valid after the cast:

AFPSGameState* GS = Cast<AFPSGameState>(GetWorld()->GameState);
const int32 VirusScore;
if (GS != nullptr) {
   VirusScore = GS->TeamScores[0];
}

Thanks that fixed that problem. Now it is saying that TeamScores[0] is out of bounds.

I figured it out. I forgot to initialize the array so there wasn’t actually anything in there. Thank you for your help though!

Can you post the code where you create and initialise your array? An error like that usually means you haven’t correctly sized your array.