-1

Please explain the output of following code. I was expecting output to be 16 but output is 8.

#include <iostream>
using namespace std;

 void xy(int arr[2][2]){
   cout << sizeof(arr);
 }

int main() {


int arr[2][2] = {{1,2},{3,4}};
xy(arr);
  return 0;
}
ashasa892
  • 3
  • 3

2 Answers2

3

When you pass an array to a function, it decays to a pointer so you're actually passing int*. sizeof will give the size of the pointer which can vary depending on the system. In this case, it's returning 8 likely because you're on a 64-bit system.

Arne
  • 1,293
  • 1
  • 7
  • 20
  • But in my system size of an int variable is 4 and also if i tries to use sizeof (2DArray) in main function then output of above code will be 16. – ashasa892 Jul 03 '19 at 02:03
  • `int` is 4-byte but to have enough space to store `int*` on a 64-bit system, 8-byte is needed. Also, if you use sizeof in main function the decay doesn't happen because the compiler know exactly how much space is allocated compared to just an integer pointer – Arne Jul 03 '19 at 02:08
  • @ashasa892 The size will be correct in the scope where the variable is declared, like main, but you lose that and it decays to a pointer when you pass it to another function. – Retired Ninja Jul 03 '19 at 02:14
  • So can you please suggest any other way to find the size of a 2d array passed into a function? – ashasa892 Jul 03 '19 at 02:15
  • 2
    Yes, use a `std::vector` or a `std::array` in C++. – Retired Ninja Jul 03 '19 at 02:18
  • 1
    or a simple way can be to pass it as a separate argument – Arne Jul 03 '19 at 02:18
0

If you want to pass a plain old C-array to a function, you have 2 possibilities.

  1. Pass by reference
  2. Pass by pointer

It seems that you want to pass by reference. But you are using the wrong syntax.

Please see:

void function1(int(&m)[3][4])   // For passing array by reference
{}
void function2(int(*m)[3][4])   // For passing array by pointer
{}

int main()
{
    int matrix[3][4]; // Define 2 dimensional array

    function1(matrix);  // Call by reference
    function2(&matrix); // Call via pointer 
    return 0;
}

What you pass to the function is a decayed pointer to array of int.

Simply correct the syntax and it will work.

Additional hint:

Do not use plain C-style arrays in C++. Never. Please use STL containers.

A M
  • 14,694
  • 5
  • 19
  • 44