how do i do that? well i want to check if the array is empty
5 Answers
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.
15 Comments
a declared with array type. Array is an object. Objects cannot reside at null address, by definition.a is declared with array type, then the check makes no sense. What I said does not apply to dynamically allocated arrays, since in that case a won't have array type.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)
3 Comments
int * array = 0; /* stuff */ array = new array[5]; will spend time with array being empty. Of course, declaring a variable that can't be initialized meaningfully is a code smell.If you are using an STL vector or list, you can use the empty or the size method to check for emptiness:
std::vector<int> v;
if (v.empty()) cout << "empty\n";
if (v.size() == 0) cout << "empty\n";
std::list<int> l;
if (l.empty()) cout << "empty\n";
if (l.size() == 0) cout << "empty\n";
A regular C++ array (like int a[]') or pointer (likeint* a) doesn't know its size.
For arrays declared with size (like int a[42] as a local or global variable or class member), you can use sizeof(a) / sizeof(a[0]) to get the declared size (42 in the example), which will usually not be 0. Arrays you declare this way are never NULL.
null, although it can decay into a pointer, and pointers can be null)