As the title suggests, I am trying to use a pointer as an array in my code but it's not working. I've read the tutorials on this site and a few others about using pointers as arrays, and as far as I can tell I'm doing things correctly, save that I keep getting an error. My pointer is declared like this:
1 2 3 4 5 6 7 8
|
#define ASTEROID_ARRAY_LENGTH 4
Asteroid *asteroids = new Asteroid[ASTERIOD_ARRAY_LENGTH];
void init()
{
for( int i = 0; i < ASTERIOD_ARRAY_LENGTH; i ++ )
asteroids[i]->spawn( (float)rand(), (float)rand() );
}
|
init() is called at the beginning of my WinMain function, as I'm coding a Windows GUI application.
The error message I get is this:
error: base operand of '->' has non-pointer type 'Asteroid'
. I am using Code::Blocks on 64-bit Windows 7, if any of that matters.
I have also tried to use malloc() and calloc() to allocate memory for my array, both with various errors revolving around the compiler not finding the Asteroid(void*) constructor. As you may have guessed, I have no clue how to fix that error either. Asteroid.h looks like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
#ifndef ASTEROID_H
#define ASTEROID_H
#include <math.h>
#include <windows.h>
#include <gl/gl.h>
#include <iostream>
#include <fstream>
#include <string>
#include "Rect.h"
class Asteroid
{
public:
Asteroid();
Asteroid( void* );
Asteroid( int );
void spawn( float, float );
void draw();
void move();
void checkIfOutside();
void enable();
void takeDamage( int );
Rect getRect();
void die();
private:
float x, y, red, green, blue, theta, xSpeed, ySpeed, rSpeed;
int health, maxHealth;
bool enabled;
//string fileName( "asteroiddebugger" );
std::ofstream debug;
Rect rect;
Utility utility;
};
#endif
|
All functions declared in that file have an implementation in Asteroid.cpp.
Undoubtedly some of you will suggest that I just use an array. For what I'm doing, an array would work extremely well. The thing is, though, I'm creating this program as a learning experience, so that I may expand my knowledge of the C++ language. Arrays would work fine, but wouldn't teach me anything.