Check if C++ Array is Null
You can use either static or "dynamic" arrays. An static array would be something like the following:
int array[5];
That represents an static array of 5 integer elements. This kind of array cannot be null, it is an array of 5 undefined integers.
A "dynamic" array, on the other hand would be something like this:
int* array = new array[5];
In this case, the pointer-to-int is pointing to an array of 5 elements. This pointer could be null, and you would check this case with a simple if statement:
if (array == 0)
An array in C++ cannot be null; only a pointer can be null.
To test whether a pointer is null, you simply test whether it compares equal to NULL
or 0
.
Array in C++ cannot be "empty". When you define an array object, you explicitly specify the exact size of the array. That array contains (and always will contain) that exact number of elements you specified in the definition. No more no less. It will never be "empty".
Actually, when you have an array a[SIZE], you can always check:
if( NULL == a )
{
/*...*/
}
But it's not necessary, unless you created a dynamic array (using operator new).
See the other answers, I won't delete it just because it's accepted now. If other answer is accepted, I'll delete this "answer".
EDIT (almost 4 years later :) )
As I get many down-votes for this, I'd like to clarify: I know this is useless and a
will never be NULL, but it technically answers the question about the NULL
part.
Yes, it does NOT mean, the array is empty, NOT at all. As @JamesMcNellis notes below, arrays cannot be NULL, only pointers.
It could only be useful for dynamically allocated arrays with initialized pointer before the allocation.
Anyway, I'll wait for accepting other answer and will delete mine.