-5

I'm trying to findout the size of the array. But instead of giving it 5 it is giving 2. Which is not correct. Formula for finding the size of the array is this. int size = sizeof(pArr)/sizeof(int); You can see the working code here. For your ease code is shown below.

#include <iostream>
void printArray(int* pArr){
    //find size of the array. It should be 5 but 
    //below it is calculating it 2. Why?
    int size = sizeof(pArr)/sizeof(int);
    std::cout << "sizeof pArr: " << size << "\n";
    for(int i=0; i<size; i++){
        std::cout << *(pArr+i);
    }
}
int main(){
    int another[] = {1,2,3,4,5};    
    printArray(another);
    for(int j=0; j<5; j++){
    // std::cout << arr[j]<< "\n ";   
    }//end for
}//end main
Superman
  • 871
  • 2
  • 13
  • 31
  • You could use the same method used [by std::end](http://stackoverflow.com/a/33496357/1708801), otherwise you have to pass the size as an argument. – Shafik Yaghmour Nov 17 '15 at 15:07
  • 3
    because sizeof(pArr) give you the size of a pointer not the size of the array – Jerome Nov 17 '15 at 15:07

1 Answers1

2

There is none. Once the array-to-pointer conversion happens, the size information is gone. If you need it, you have to pass the size as a separate argument.

Since pArr is a pointer, sizeof(pArr) gives the size of the pointer. Your pointers seem to be double the size of ints; that is the case on x86-64, for example.

One option to preserve the size would be to turn the processing function into a function template parameterised on the array size:

template <std::size_t N>
void printArray(int (&arr)[N])
{
  for (std::size_t i = 0; i < N; ++i) {
    std::cout << arr[i];
  }
}

Note that this means you'll normally need to implement the template in a header file, and you'll get one instantiation for each array size with which you call it. And it will only be callable with actual C-style arrays.

Community
  • 1
  • 1
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455