Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using sizeof() in an initialized, unknown size array - C++

I'm new to C++ programming and I'm trying to get the size of an array. Can anybody explain me why this happens? I've tried running the code in runnable.com and the same result shows.

I'm sure this is not the right way to do it. If possible, can you suggest any EASY way to get the size of that kind of array?

#include <iostream>

using namespace std;

int main ()
{
  int set1[] = {1, 9, 3, 50, 31, 65};
  int set234[] = {3, 5, 5};

  cout << sizeof(set1) << endl;
  cout << sizeof(set234) << endl;

  cout << "When sizeof() return value is divided by 4"<< endl;
  cout << sizeof(set1) / 4 << endl; 
  cout << sizeof(set234) / 4 << endl;

  return 0;
}

****************************************************************
Output:
24
12
When sizeof() return value is divided by 4
6
3
****************************************************************

**EDIT : Thank you for your responses. flies away :D

like image 883
NOWA Avatar asked Sep 02 '14 17:09

NOWA


2 Answers

The size of an array is equal to the sum of sizes of all its elements. As in your example you deal with arrays of type int then it seems sizeof( int ) in your system is equal to 4, So as the first array has 6 elements then its size is equal to 6 * sizeof( int )that is 24. The size of the second array is equal to 3 * sizeof( int )that is 12. If for example sizeof( int ) in your system would be equal to 8 then the size of the first array would be equal to 48 ( 6 * sizeof* int ) ) and the size of the second array would be equal to 24 ( 3 * sizeof( int ) ).

So if you want for example to know how many elements there are in an array you can calculate this the following way

sizeof( YouArray ) / sizeof( YourArray[0] )

or

sizeof( YouArray ) / sizeof( ElementType )
like image 116
Vlad from Moscow Avatar answered Oct 29 '22 17:10

Vlad from Moscow


sizeof returns the number of bytes, not the number of elements. Mostly you should avoid arrays; use std::vector or std::array, both provide an easy way to get the number of elements.

like image 23
Alan Stokes Avatar answered Oct 29 '22 15:10

Alan Stokes