Link to home
Start Free TrialLog in
Avatar of jt9812
jt9812

asked on

Dynamic array definition in C++

Hello-- could someone please explain to me why the following C++ code is printing 2 and not 5?

# include <iostream>
using namespace std;

int main(){

    int *foo;
    foo = new int[5];

    cout << sizeof(foo) / sizeof(foo[0]) << endl;

    delete[] foo;

    return 0;

}


Thank you!
Avatar of it_saige
it_saige
Flag of United States of America image

Because sizeof is not returning the length of the array but rather the size of the type:

http://en.cppreference.com/w/cpp/language/sizeof

In this case the size of a pointer (which is 8 on a 64-bit system) and the size of an integer (which is 4).

-saige-
SOLUTION
Avatar of Zoppo
Zoppo
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial