Вопрос

I have a simple class called tire. Now I want to dynamically allocate the number of tires for a vehicle when a vehicle object is created. For this, I want to create an array of tire-class objects with size equal to the number of tires. To check my code, I would like to print the number of objects in the tire-class array.

The question is: Is there a function which can check how many elements are in my tire class array? Can I use the sizeof() function?

Here is the code:

#include <iostream>

// create a class for the tires:
class TireClass {
public:
    float * profileDepths;
};

// create class for the vehicle
class vehicle {
public:
    int numberOfTires;
    TireClass * tires;
    int allocateTires();
};

// method to allocate array of tire-objects
int vehicle::allocateTires() {
    tires = new TireClass[numberOfTires];

    return 0;
};

// main function
int main() {
    vehicle audi;
    audi.numberOfTires = 4;
    audi.allocateTires();

    // check if the correct number of tires has been allocated
    printf("The car has %d tires.", sizeof(audi.tires));

    // free space
    delete [] audi.tires;

    return 0;
};
Это было полезно?

Решение 2

Well, what happens when you run the code? Does it change if you compile in 32 or 64 bit mode, if you have the facility?

What's happening is that you're asking the compiler to tell you the storage size (in bytes) needed to hold the tires variable. This variable has type TyreClass*, so the storage size is that needed for a data pointer: this might be anything, but today it will probably be 4 bytes for a 32-bit system, or 8 bytes for a 64-bit system.

Whilst it's possible to use sizeof to tell you the size of a statically allocated array, it's not possible for dynamic (heap) allocation. The sizeof operator (in C++, at least) works at compile time, whereas dynamically allocating memory is done when your programme runs.

Much better, for all sorts of reasons, would be to use a std::vector<TyreClass> to hold your tyres. You can then easily get the number of tyres stored, and don't have to worry about allocating or deallocating arrays yourself.

(EDIT: Gah, forgive me mixing up english/american spellings of tyre/tire. It's late and I'm tyred.)

Другие советы

No, there's none. Consider using std::vector. Or just store tires count in some other variable (maybe numberOfTires is good enough?).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top