How to access an array element from a pointer?

I’m having problems with this code

header:

protected:

	virtual void BeginPlay() override;

	// Arrays of all of the spawn points that are available
	TArray<ASSpawnPoint*> TeamOneSpawnPads, TeamTwoSpawnPads;

	// Integers that hold the number of players on each team
	int32 TeamOneAmount, TeamTwoAmount;

cpp:

FVector ASGameMode::GetSpawnLocation(int32 Team)
{
	FVector NewSpawnLocation = FVector(0.0f);
	TArray<ASSpawnPoint*>* SpawnPads;

	// Set up an array that points to the correct teams spawn point array
	if (Team == 1)
	{
		SpawnPads = &TeamOneSpawnPads;
	}
	else
	{
		SpawnPads = &TeamTwoSpawnPads;
	}
	
	// Generate a random number that we will use to reference a spawn pad
	int32 RandomSpawnerInt = FMath::FRandRange(0.0f, SpawnPads->Num() - 1);

	// Get a reference to the spawn pad we will be using
    // I'm pretty sure this is what is causing problems
	ASSpawnPoint* SpawnPad = SpawnPads[RandomSpawnerInt];

	// Set the location that we will return to the location we get from the spawn pad
	NewSpawnLocation = SpawnPad->GetRespawnLocation();

	// Remove the spawn pad from the availability array
	SpawnPads.Remove(SpawnPads[RandomSpawnerInt]);
	
	return NewSpawnLocation;
}

Returns:

(21): `error C2440: 'initializing': cannot convert from 'TArray<ASSpawnPoint *,FDefaultAllocator>' to 'ASSpawnPoint *&'

When I changed TArray<ASSpawnPoint*>* SpawnPads; to TArray<ASSpawnPoint*> SpawnPads; I got a HUGE amount of errors.

You need to deference the array pointer to use the [] operator.

ASSpawnPoint* SpawnPad = SpawnPads[RandomSpawnerInt];

to

ASSpawnPoint* SpawnPad = (*SpawnPads)[RandomSpawnerInt];
3 Likes

Thank you! I’ve been trying to figure this out for days.

1 Like