-3

When I changed the code to include an argument for size, the code worked correctly. But I cannot understand the error it is showing when I'm calculating length of array using sizeof() ?

#include <iostream>
using namespace std;

void display(int arr[]){
    int n=sizeof(arr)/sizeof(arr[0]);
    int* ptr=arr;
    for (int i=0;i<n;i++) {
        cout << i << " : " << *ptr << endl;
        ptr++;
    }
} 

int main(){
    int arr[9] = {2,5,3,8,5,4,6,1,7};
    display(arr);   
    return 0;
}
utkarshd3
  • 11
  • 1

1 Answers1

4
void display(int arr[], int n)

This is a lie, but that's not your fault.

During compilation it is automatically re-written to:

void display(int* arr, int n)

That is, although arrays are not pointers, silly old C features can make us think that they are! It is impossible to pass an array by value so you're really just passing a pointer to the first element.

As such, you're doing sizeof(int*).

Instead, I suggest using sizeof(*arr) * n, or pass a reference to the array:

#include <iostream>

template <std::size_t N>
void display(const int (&arr)[N])
{
    std::size_t i = 0;
    for (std::size_t i = 0; i < N; i++)
        std::cout << i << " : " << arr[i] << '\n';
} 

int main(){
    int arr[9] = {2,5,3,8,5,4,6,1,7};
    display(arr);
}

(live demo)

… or rewrite your function to take an iterator pair instead:

#include <iostream>
#include <iterator>

template <typename It>
void display(const It begin, const It end)
{
    std::size_t i = 0;
    for (It it = begin; it != end; ++it)
        std::cout << i++ << " : " << *it << '\n';
} 

int main(){
    int arr[9] = {2,5,3,8,5,4,6,1,7};
    display(std::begin(arr), std::end(arr));
}

(live demo)

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055