c++arraysstruct

Get the number of elements in a struct array c++


I need to find the number of elements in a struct array

I have this struct

struct Features {
    int feature1;
    string feature2;
    string feature3;
    string feature4;
    bool feature5;
};

I have then turned it into an array

Features *feature = new Features[100];

I have then entered some values

for(int i = 0; i < 3; i++)
{
    feature[i].feature1 = 5;
    feature[i].feature2 = "test";
    feature[i].feature3 = "test2";
    feature[i].feature4 = "test3";
    feature[i].feature5 = true;
}

now I want to get the size of the array, which should be 3 (2)

How do I do this?

cout << (sizeof feature / sizeof *feature) << endl;

doesn't seem to work as it prints the incorrect value. (It keep printing 4)

Sorry if this is a stupid question, I am still learning c++


Solution

  • No, actually the size of the array is 100, not 3, because you allocated a 100-element array with new. The fact that you initialized 3 elements in the array doesn't matter. It's still is a 100 element array.

    But whether it's 3, or 100, it doesn't matter. It's up to you to keep track of the size of the allocated array. C++ doesn't do it for you.

    But if you do want for C++ to keep track of the size of the array, use std::vector. That's what it's there for.