-1

I have written the following code block. But the size of the array returned by sizeof() is irrelevant. I have an array of 6 elements while the sizeof() returns 24 as the size of the array.

Here is the code:

#include "stdafx.h"
#include <iostream>

using namespace std;

int main()
{
    int arr[6] = { 0, 5, 8, 32, 100, 41 };
    int arrSize = sizeof(arr);
    int i = 0;
    cout << "This is the Size of Array: " << arrSize << endl;
    /*
    for (i = 0; i < arrSize; ++i)
    {
      cout << arr[i] << endl;
    }   */

    return 0;
}

And here is the Output:

This is the Size of Array: 24
Mostafa Talebi
  • 8,825
  • 16
  • 61
  • 105

2 Answers2

2

You should do

int size = sizeof(arr)/sizeof(arr[0]);

This would find total size of array ie. here 6 * 4 = 24 and then divide it by single element size, hence 24/4 = 6

sujithvm
  • 2,351
  • 3
  • 15
  • 16
1

sizeof gives the size of the data in bytes

6 * 4 byte integers = 24 bytes

Josh B
  • 1,748
  • 16
  • 19