0
#include <iostream>
using namespace std;

int binarySearch(int inArray[], double targetVal)
{
  int lowIndex = 0;
  int upIndex = (sizeof(inArray)/sizeof(inArray[0]));
  int middleIndex = (lowIndex + upIndex) / 2;

  cout << sizeof(inArray) << endl;

  cout << inArray[3] << endl;

  // cout << upIndex << endl;

}

int main()
{
  int a[4] = {0 , 1 , 3, 5};

  cout << sizeof(a) << endl;

  // cout << sizeof(a)/sizeof(*a) << endl;

  binarySearch(a , 3);
}

This is the relevant code. In main(), sizeof(a) outputs 16. in binarySearch(), sizeof(inArray) outputs 8. Could someone explain to me why there isa difference? Array a should be identical to inArray?

lawson123
  • 21
  • 2
  • One is giving you 4 integers * 4 bytes = 16 and the other is giving you the size of a pointer = 8 bytes. – Khalil Khalaf Sep 26 '16 at 16:17
  • For more on that, [What is array decaying?](http://stackoverflow.com/questions/1461432/what-is-array-decaying) – user4581301 Sep 26 '16 at 16:19
  • Oh I see. Is there a way to find the total size of the array inside the function without knowing the number of elements? – lawson123 Sep 26 '16 at 16:25
  • No, there is no way, sizeof will just give you the size of the pointer. I think the best solution for you is likely to use `std::vector` or maybe wrap up the array yourself. If you use a vector you could say something like `cout << sizeof(int) * arr.size();` or just `arr.size();` to give you the number of elements stored. – George Sep 26 '16 at 16:50

0 Answers0