Share via


More on Getting the Number of Array Elements

In a previous post, I discussed a safer way to get the number of elements in a C++ array. I mentioned that the countof() macro doesn’t work with local types (i.e. types defined inside a function definition).

I just realized that the macro also fails to work with anonymous types under certain circumstances. To be exact, If you call countof() on two arrays that have different anonymous types AND same size, then the second call will fail to compile.

e.g.

struct

{

    int x;

} g_a[100];

struct

{

    int x;

} g_b[100];

    int g_size;

   

    g_size = countof( g_a ); // First call - OK

    g_size = countof( g_b ); // Second call - compiler ERROR!

The reason is that in this case, the second instantiation of the template helper function _ArraySizeHelper clashes with the first instantiation.

Note that if you change the size of g_b to something other than 100, it compiles fine.

So the caveat should be “countof() does not work with local types, and under certain circumstances does not work with anonymous types.”

I cannot believe it’s so difficult to get such a simple job (getting the number of array elements) done in C++.

What a broken language it is.

Comments

  • Anonymous
    October 06, 2004
    Truly, your gripe is more appropriately aimed at C. In C++, you can use a vector<T> which knows its size and will grow for you.
  • Anonymous
    October 07, 2004
    Dear STL Dude,

    I want to know the size of the array at compile time. vector<T> doesn't give me that.
  • Anonymous
    October 16, 2004
    Does anyone know how to get a count for a pointer to an array

    for example

    double** someFnct () {

    cout <<"Enter num of row: " <<endl;
    cin >> n;

    cout <<"Enter num of column: " <<endl;
    cin >> m;

    double** matrixX = new double[n];
    for (int i = 0; i<numOfRows; i++) [
    matrixX[i] = new double(m);
    }
    return matrixX;
    }

    double** tmpMtrx = someFunct();

    int row = sizeof tmpMtrx / sizeof* tmpMtrx; // does not work
    int column = // don't even know where to begin with this one


    Any insight would be greatly appreciated. Thanks