-1

The code in question is:

int* array = new int;
int array2[] = {2,3,4,5,6};
int noOfEl, i;
cin>> noOfEl;
for(i=0; i<noOfEl; i++)
   cin>> array[i];
cout<< "SizeOfArray-> " << sizeof(array) << endl;
cout<< "SizeOfOneEl-> " << sizeof(array[0]) << endl;
cout<< "SizeOfArray2-> " << sizeof(array2);

The input file is input.in which looks like:

4
8
2
17
9

And the output I am getting is:

SizeOfArray-> 4
SizeOfOneEl-> 4
SizeOfArray2-> 20

Why?

Shouldn't it be 20 in case of array as well?

HindK
  • 143
  • 1
  • 1
  • 9
  • array is just one integer. –  Aug 16 '14 at 19:07
  • 1
    Here's a clue: if you compile and run this on a 64-bit machine, the first line will print `8`. Please read [this](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c) in its entirety. – Praetorian Aug 16 '14 at 19:08
  • 3
    `array` is not an array. It's a pointer. – n. m. could be an AI Aug 16 '14 at 19:09
  • @n.m.But as is array2. – HindK Aug 16 '14 at 19:10
  • 1
    @HindK, No, `array2` is an [array](http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c). You also can't expect `noOfEl` to be greater than 1 and have your program exhibit any kind of normal behaviour. – chris Aug 16 '14 at 19:11
  • 2
    BTW, you write out of bound of `array` – Jarod42 Aug 16 '14 at 19:11
  • Can you tell `*` from `[]`? If it has a `*` it's a pointer. If it has a `[]` it's an array. Well, not always, just most of the time, but you should use neither arrays nor pointers anyway, so it doesn't really matter. – n. m. could be an AI Aug 16 '14 at 19:15
  • Praetorian may be a bit quib but his link is good http://stackoverflow.com/questions/4810664/how-do-i-use-arrays-in-c I think you would benifit from that high quality post – odinthenerd Aug 16 '14 at 19:23
  • As @Jarod42 said, your code makes _undefined behavior_ by writing out of bound of `array` in `for` loop in your code, when program reads number greater than 1 from _stdin_ in line `cin>> noOfEl`. To fix it, you have to change the `for` loop, or the `array`'s size. – GingerPlusPlus Aug 18 '14 at 21:16

2 Answers2

2

Your output is expected:

  • array is a pointer to an int, so sizeof(array) returns the size of a pointer on your implementation.

  • array[0] is an int, so sizeof(array[0]) returns the size of an int on your implementation.

  • array2 is an array : sizeof(array2) returns the total size of the array (N * sizeof(int))

quantdev
  • 23,517
  • 5
  • 55
  • 88
2
  • sizeof(array) == sizeof (int*)
  • sizeof(array[0]) == sizeof (int)
  • sizeof(array2) == sizeof(int[5]) == 5 * sizeof (int)
Jarod42
  • 203,559
  • 14
  • 181
  • 302