FRIHOST • FORUMS • SEARCH • FAQ • TOS • BLOGS • COMPETITIONS
You are invited to Log in or Register a free Frihost Account!


length of an int array c++





Denvis
Code:
int i[] = {1,2,3,4,5,6,7,8,9,0}

sizeof(i)/sizeof(i[0])


Can anybody explain how that can give me the length of the array?

Thanks
Fire Boar
Pretty simple. sizeof(i) will return the total amount of memory used for i. sizeof(i[0]) will return the amount of memory used for one element of i. So the former divided by the latter is the total number of elements in i.
Peterssidan
What Fire Boar says is correct.

in C/C++ it is very common to access an array through a pointer. In that case this will not work, so be careful. The following code shows the problem.
Code:
int i[] = {1,2,3,4,5,6,7,8,9,0};
int *j = i;
std::cout << "length of i: " << sizeof(i)/sizeof(i[0]) << std::endl;
std::cout << "length of j: " << sizeof(j)/sizeof(j[0]) << std::endl; // wrong!

The above code gives the wrong array length for j.

A better solution is to create a template function that takes a reference to an array and return it's size. That way we get a compile time error if we try to use it on a pointer but works perfect when used on a real array.
Code:
template <typename T, std::size_t N>
std::size_t array_length(const T (&array)[N])
{
    return N;
}

Code:
array_length(i); // returns 10
array_length(j); // error: no matching function call to 'array_length(int*&)'
Related topics
Image Processing in C++ by Shirish
Fortran Tutorials(77)
C/C++
A C program in Linux
C program with 3D array, in Linux
Dynamic arrangement of buttons in C# Win Form
[C] Splitting names program
Is faith necessary?
C++ An Inline Question
C++ Return array from function
c++ ile programlamaya giriώ
Is true bool always converted to 1?
How to call the method?
Recursive functions in java
Reply to topic    Frihost Forum Index -> Scripting -> Others

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.