Home > OS >  Why does size of array differ in main and other function?
Why does size of array differ in main and other function?

Time:10-02

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.

CodePudding user response:

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>?

CodePudding user response:

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

  • Related