If I write
int main()
{
int a[100] = {1,2,3,4,};
cout<
A pointer is a pointer. That means, it simply points to memory, and that's all about it. Creating a pointer to an array (which usually means a pointer to the first element of the array, but not necessarily) is still only a pointer to some memory location. As a memory address is simply a memory address there is also no way for the pointer to know that the memory it is pointing to originally was an array, or how long that array was.
It's simply how pointers work. They point to memory, and that's all.
When passing your array as a parameter to a function taking a pointer, the array decays as a pointer.
void bar(int *a)
{
std::cout << sizeof(a) << std::endl; // outputs "4" (on a 32 bit compiler)
}
void foo()
{
int a[100] ;
std::cout << sizeof(a) << std::endl; // outputs "400" (on a 32 bit compiler)
bar(a);
}
So perhaps the solution is to provide a correct function taking a reference to an array as a parameter :
template <size_t T_Size>
void bar(int (&a)[T_Size])
{
std::cout << T_Size << std::endl; // outputs "100" (on ALL compilers)
std::cout << sizeof(a) << std::endl; // outputs "400" (on a 32 bit compiler)
}
void foo()
{
int a[100] ;
std::cout << sizeof(a) << std::endl; // outputs "400" (on a 32 bit compiler)
bar(a);
}
Of course, the function must be templated.
Arrays decay to pointers when passed to functions, so all you will get is the size of the pointer.
This isn't working because sizeof is calculated at compile-time. The function has no information about the size of its parameter (it only knows that it points to a memory address).
Consider using an STL vector instead, or passing in array sizes as parameters to functions.
This was answered by Marcel Guzman in Calculating size of an array!
No. You are wrong.
If I run your second part of code, it gives 1 on my computer. It's not 400.
#include <iostream>
void func(int *a);
using namespace std;
int main()
{
int a[100] = {1,2,3,4,};
func(a);
return 0;
}
void func(int *a)
{
cout<<sizeof(a)/sizeof(a[0])<<endl;
}
Produces
1
You get 400 the first time because you are passing only sizeof(a), not sizeof(a)/sizeof(a[0]), to cout. You need to wrap that calculation with parenthesis to get the correct value outputted, ie:
cout << (sizeof(a)/sizeof(a[0])) << endl;
For the second time, you should be getting 2, 4, or 8 (depending on architecture), definately not 400, since you are essentially outputting this:
cout << sizeof(int*) << endl;
Where the size of a generic pointer is always a fixed value.