0

I am not new to C++, but today I found that the size of the array is different in the main function and in other functions. Why is that? I suppose it's something related to pointers.

#include<bits/stdc++.h>
using namespace std;

void func(int arr[]){
    cout<<"func size: "<<sizeof(arr)<<"\n";
}

int main(){
    int arr[5];
    cout<<sizeof(arr)<<"\n";
    func(arr);
    return 0;
}

You can test this code to see the difference.

asmmo
  • 6,922
  • 1
  • 11
  • 25
virteanchi
  • 169
  • 1
  • 14
  • 4
    It's known as [array to pointer decay](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay). When you pass the array to a function, the size information is lost. This is why many C functions that act on arrays take an array argument and a size argument, and why in C++ it's preferred to use classes like `std::array` that offer value semantics. – Nathan Pierson Oct 02 '21 at 04:54
  • Okay, thank you! That explains everything. – virteanchi Oct 02 '21 at 04:57

3 Answers3

5

Because the array is decayed to a pointer What is array to pointer decay?.

you can pass the array by reference to see the same size, as follows

#include <iostream>

template <class T, size_t n> void func(T (&arr)[n]) {
    std::cout << "func size: " << sizeof(arr) << "\n";
}

int main() {
    int arr[5];
    std::cout << sizeof(arr) << "\n";
    func(arr);
}

Demo

And see Why is "using namespace std;" considered bad practice? and Why should I not #include <bits/stdc++.h>?

asmmo
  • 6,922
  • 1
  • 11
  • 25
2

The question has been already been answered accurately. However, if you want to be on the safe side, there are compiler flags that can point out for you during compilation only. Use the -Wall flag you will get a warning like this

'warning: ‘sizeof’ on array function parameter ‘arr’ will return size of ‘int*’ [-Wsizeof-array-argument]'

note: declared here
4 | void func(int arr[]){

I assume you are not using flags.

Also from c++20 you can use std::ssize() instead of sizeof()

std::size and std :: ssize

Ryednap
  • 324
  • 1
  • 9
1

In main function cout return side of array but when u pass in func function it was printing address that's why both are not same.for your verification u can check address of array in both main and function below is code. #include<stdio.h>

using namespace std;
void func(int arr[]) {
  cout << "func size: " << sizeof( & arr) << "\n";
                                 }

int main() {
  int arr[5];
  cout << sizeof( & arr) << "\n";
  func(arr);
  return 0;
                    }