how do i do that? well i want to check if the array is empty
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
.
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).
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".
Answer to your new question:
An array is only a pointer to the first element of the array. The following elements are stored after the first one. So this means in C++, you have no "arrays" like you know them from Java. It is only a pointer. And a pointer has a size depending on your architecture (x64 or x86).
This means you have two possible solutions:
- Make use of the
vector
class, which keeps the array size for you. - Let join an integer the usage of arrays everywhere in C++, which represents the size.
Answer to your previous question:
So this means you have to check if the pointer to the first element is null.
int myIntArray[30]; // Create an int-array on the stack.
if (myIntArray == 0)
{
printf("I'm crazy!!! This code will never be executed");
}
int *myIntArray = new myIntArray[30]; // Create array on the heap
if (myIntArray == 0)
{
// Same as here above
}
int *myPointerToInt = 0;
if (myPointerToInt == 0)
{
// Do whatever you want
}
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)
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 (like
int* 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
.