Tag Archive | c++

Length of Array (and no we can’t always know that)

One way of checking whether an array is allocated correctly is the check if there are as many cells as you think there was going to be. In C++, this can be done using sizeof operator. Sizeof output the number of bytes an variable is taking up. So the size of an array can be found using the command

int num=5;
double array[num];

size=sizeof(array)/sizeof(*array);

Hang on! What’s the size of *array? Usually the asterisk indicate you’re working with a pointer. Basically, this part output the size of the variable contained in the first cell of the array.sizeof(array) gives the size of the entire array, so the code gives you the number of cells.

However, this method doesn’t work if the array is allocated dynamically using

int num=5;
double* array;

array=new double[num];

If we try to find the size using

size=sizeof(array)/sizeof(*array);

the result will be 1. Why is that? This is because array is declared as a pointer of type double, so it gives the size of a double variable, unlike when array is allocated statically. The sizeof(*array) will also give the size of a double variable. So no matter how large num is, this method will always give the size of 1.

How can we find the size of a dynamically allocated array? I don’t know a work around that doesn’t involve knowing the size of the array, because the array wouldn’t have any information that allows us to infer the size of the array.