Insecure array size!

Why does ARRAY_SIZE work only in 'main' and not in 'printarray'?

#include <iostream>
#define ARRAY_SIZE(array) ((sizeof(array))/sizeof(array[0])) //array size

void printarray (int arg[])
{
int length = ARRAY_SIZE(arg); //why is ARRAY_SIZE(arg) only 1 ?

for (int n=0; n<length; ++n) //length==1 so only first element is printed
std::cout << arg[n] << ' ';

std::cout << '\n';

for(int elem : arg) //also, why does this give an error?
std::cout << elem << " ";
}

int main ()
{
int myAarray[] = {5, 10, 15};

std::cout << ARRAY_SIZE(myAarray); //in main, works perfectly

printarray (myAarray);
}
Because arg is a pointer (a pointer to first element in the array) so sizeof(arg) gives you the size of a pointer which has nothing to do with the size of the array.

May I suggest using std::vector?
http://www.cplusplus.com/reference/vector/vector/
To clarify, the word usually used is that an array decays in to a pointer when passed into a function.
Read https://stackoverflow.com/questions/1461432/what-is-array-decaying for more info.

But I totally suggest using vectors as well, in general. std::vector keeps track of its own size through my_vector.size() function.
Last edited on
Topic archived. No new replies allowed.