In this small example, c++ forgets size of an array, passed to a constructor. I guess it is something simple, but I cannot see it.
In classes.h, there is this code:
#ifndef CLASSES_INC
#define CLASSES_INC
#include <iostream>
class static_class {
public:
static_class(int array[]) {
std::cout<<sizeof(array)/sizeof(int)<<"\n";
}
};
class my_class{
public:
static static_class s;
static int array[4];
};
#endif
In classes.cpp, there is this code:
#include "classes.h"
int my_class::array[4]={1, 2, 3, 4};
static_class my_class::s = static_class(my_class::array);
In main.cpp, there is only simple
#include "classes.h"
int main () {
return 0;
}
Now, the desired output (from the constructor of static_class) is 4. But what I get is 1. Why is that?
edit:
A lot of answers suggest that sizeof on pointer returns the size of a pointer. That is not true, AFAIK (from http://msdn.microsoft.com/en-us/library/4s7x1k91(VS.71).aspx – “When the sizeof operator is applied to an array, it yields the total number of bytes in that array, not the size of the pointer represented by the array identifier.”)
edit2:
ok, as I found out, when compiler can see the size, sizeof returns the whole size, but when it decays to a pointer (which is the case here), sizeof actually really returns size of pointer.
When declaring a function parameter, the following two are equivalent because an array decays to a pointer when it is passed as an argument:
So, you end up computing
sizeof(int*) / sizeof(int), which happens to be one on your platform because their sizes are the same.If you need the size of the array in your function, you should pass it as an argument to the function, or use a container that keeps track of the size for you.