Get Upper and lower bound of an array at runtime.

A silly question,please help me.
can I get the Upper & lower bound of an array at runtime?

example:
  TCHAR SomeArray[]= {
                      "aaa",
                      "bbb",
                      ...
                     };

...
if ( (dwIndex >=0) &&(dwIndex < UPPER_BOUND_OF(SomeArray))
{
  do something ...
}

what is the UPPER_BOUND_OF() should be?
FreateAsked:
Who is Participating?
 
chensuConnect With a Mentor Commented:
#define  UPPER_BOUND_OF(a) (sizeof(a) / sizeof(a[0]))

The definition of your array is incorrect. It should be

LPCTSTR SomeArray[]= {
                      "aaa",
                      "bbb",
                      ...
                     };
0
 
jasonclarkeCommented:
But this will only work with statically allocated or automatically allocated arrays where you are within the same scope, right?

So, this would not work:

void processArray(int* a)
{
    cout << UPPER_BOUND_OF(a) << endl; // Incorrect Value! Will probably be 1 in this case.
}

void main()
{
    int array[20];
    cout << UPPER_BOUND_OF(array) << endl; // OK Here.
    processArray(array);
}

So, I think the answer is that there is no easy way to do this with C style arrays in general.  Which is usually why you see the size of the array passed into a function in cases like this.  i.e. you would have:

void processArray(int* a, size_t size)
{
....
}

a better solution is not to use C style arrays at all and use something like the STL vector class instead.
   

0
 
chensuCommented:
In that case, I would say that is a pointer (int *) instead of an array (int []) though they are almost the same. Besides passing the size as jasonclarke showed, you may also use a special number that is not being used as the terminator of the array.
0
 
FreateAuthor Commented:
Thank you all.
in fact I'm a Delphi programmer before,
and this is easy in delphi.

when i move to c, I found STL is very useful,but i have not even be familar with some basic C/C++ problems.

btw, thank jasonclarke too.
your comment is very helpful.
0
All Courses

From novice to tech pro — start learning today.