Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Size of an array C++ [duplicate]

Tags:

c++

arrays

size

Possible Duplicate:
Sizeof array passed as parameter

I was wondering why the output of the following code is 1 and 9. Is that because of undeclared array in function size? How can I separate "size of array" to a function?

#include "stdafx.h"
#include <iostream>
using namespace std;

int size(int a[])
{
    return sizeof a/sizeof a[0];
}

int main()
{   
    int a[] = {5,2,4,7,1,8,9,10,6};
    cout << size(a) << endl;
    cout << sizeof a/sizeof a[0] << endl;
    system("pause");
    return 0;
}
like image 981
toi la toi Avatar asked Nov 21 '12 09:11

toi la toi


2 Answers

When you write size(a) then you're passing a pointer and not an array. Since the size of a pointer and an int is 4 or 8 (depending on ABI), you get sizeof(int *)/sizeof int (4/4=1 for 32-bit machines and 8/4=2 for 64-bit ones) which is 1 or 2.

In C++ when pass an array as an argument to a function, actually you're passing a pointer to an array.

like image 81
Maroun Avatar answered Nov 06 '22 23:11

Maroun


Maroun85 answer is correct. This is not obvious but a in int size(int a[]) is a pointer.

But why don't you do it the c++ way. Using std::vectors

std::vector<int> a = {5,2,4,7,1,8,9,10,6};
cout << a.size() << endl;

no tricks here

-- edit

If your compiler does not support c++11. You can do:

std::vector<int> a;
a.push(5);
a.push(2);
...
cout << a.size() << endl;
like image 31
log0 Avatar answered Nov 06 '22 22:11

log0