sizeof arrary

N

Nan Li

Please look at the code and run below. My question is why the compiler
cannot figure out the size of the array in function foo? Is this a bug
or expected?
Thanks a lot.


#include <iostream>

using namespace std;

int a[] = { 1, 2 };

void foo( int a[2] )
{

cout << sizeof( a ) << endl;
}

int main()
{
cout << sizeof( a ) << endl;
foo ( a );
}

[nan@xxx xxx]$ g++ test.cxx && ./a.out
8
4
 
D

David Barkol

The prototype for the function foo actually takes a pointer to an int,
not an array. In the main routine you are getting the size of the
array, local variable 'a' but in the function foo you are actually
passing in a pointer. So when you get the sizeof 'a' in foo you are
getting the size of an int pointer.

David Barkol
www.neudesic.com
 
G

Gianni Mariani

Nan said:
Please look at the code and run below. My question is why the compiler
cannot figure out the size of the array in function foo? Is this a bug
or expected?

It is expected. Passing arrays is a little strange in C and by default
in C++. This is one of the reasons that passing std::vector<> is
preferred since it is more intuitive.

In C (and C++), arrays get degraded to a pointer to the first element.
However in C++ you can pass by reference which can be used to find the
size of the array, in fact, using templates, you can write generic code
that will determine the array size for you.
Thanks a lot.


#include <iostream>

using namespace std;

int a[] = { 1, 2 };

void foo( int a[2] )

replace with this:

void foo( int (&a)[2] )
{

cout << sizeof( a ) << endl;
}

int main()
{
cout << sizeof( a ) << endl;
foo ( a );
}

[nan@xxx xxx]$ g++ test.cxx && ./a.out
8
4

If you want it to work for arrays of any size use:
template <unsigned N>
void foo( int (&a)[N] )
{
cout << sizeof( a ) << endl;
cout << N * sizeof( *a ) << endl;
}
 
R

Rolf Magnus

Nan said:
Please look at the code and run below. My question is why the compiler
cannot figure out the size of the array in function foo?

Because you don't pass the array to foo. You actually pass a pointer to it's
first element.

void foo( int a[2] )

is 100% equivalent to:

void foo( int* a )

Therefore, sizeof(a) will give you the size of a pointer to int, not the
size of your array.

What you can do is make the function take a reference to an array:

void foo( int (&a)[2])
Is this a bug or expected?

It's how C++ is defined. So it's not a bug in the compiler, but you might
argue that it's a design flaw in C++ itself.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top