1
#include<iostream>
#include <string>
using namespace std;


void show_length(int array1[]){
int length=sizeof(array1)/sizeof(array1[0]);
cout<<"Length inside function = "<<length<<"\n";

}

int main(){
int array1[6]={3,6,4,2,1,4};

int length=sizeof(array1)/sizeof(array1[0]);
cout<<"Length inside main = "<<length<<"\n";
show_length(array1);

system("pause");
}

i recive 6 as an answer in the main (which is the right answer) but 2 in the separate function, why this happens?

  • 1
    In `show_length` `array1` is not an array, it's a pointer. – john Aug 18 '22 at 09:10
  • 2
    use `std::array` or `std::vector` they have a member `size()`. Or [`std::size`](https://en.cppreference.com/w/cpp/iterator/size) to get an error in the function – 463035818_is_not_an_ai Aug 18 '22 at 09:12
  • `void show_length(int array1[])` is the same as `void show_length(int* array1)` the size of a `int*` on your platform is 2 – 463035818_is_not_an_ai Aug 18 '22 at 09:13
  • Along with the other duplicates try this. It's an idiosyncrasy of C inescapably inherited by C++. Don't use 'raw' arrays in C++. They're weird. https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay – Persixty Aug 18 '22 at 09:16

0 Answers0