0

In the below program, I have a function called "change" which take a 2D array as input and return an integer value. I expected that the array is local variable and its value will not be changed in main function, but unexpectedly, it is not the case. Why does this happen?

#include <cstdio>
#include <iostream>
using namespace std;

int change(int arr[2][5]) {
  int b;

  b = 1;
  arr[0][0]=0;
  return b;
}

int main(){
    int i,j, b;
    
  int arr[2][5] =
    {
        {1,8,12,20,25},
        {5,9,13,24,26}
    };

  cout << "input array \n";

  for (i=0; i<2; i++) {
    for (j=0; j<5; j++) {
      cout << arr[i][j] << "  ";
    }
    cout << "\n";
  }
  cout << "\n";

  b = change(arr);

  cout << "final array \n";

  for (i=0; i<2; i++) {
    for (j=0; j<5; j++) {
      cout << arr[i][j] << "  ";
    }
    cout << "\n";
  }
  cout << "\n";

  return 0;
}

The output I got is:

input array 
1  8  12  20  25  
5  9  13  24  26  

final array 
0  8  12  20  25  
5  9  13  24  26  

Hoa Trinh
  • 11
  • 3
  • That's because your array decays to a pointer and the pointer to the original array is passed instead. Check out [this](https://stackoverflow.com/a/17569578/6205379) answer. – Timo Apr 07 '21 at 07:18
  • Unrelated: Why `#include `? You're not using anything from that header. – Ted Lyngmo Apr 07 '21 at 07:20
  • To work around this decay you can change your array from `int arr[2][5]` to `std::array, 2>> arr` and `#include ` – Timo Apr 07 '21 at 07:20
  • `change` actually takes a pointer to an array with five elements (it's equivalent to `int change(int (*arr)[5])`. Read about how arrays decay to pointers, and the slightly weird parameter type syntax, in your favourite C++ book. – molbdnilo Apr 07 '21 at 07:22
  • @TedLyngmo yeah, I simplified the code from my actual code and forgot to remove that. Thanks for pointing it out. – Hoa Trinh Apr 07 '21 at 07:25
  • @HoaTrinh You're welcome! I happened to notice that you haven't accepted a single answer you've gotten to your questions. Is that because they didn't help or haven't you read [What should I do when someone answers my question?](https://stackoverflow.com/help/someone-answers)? – Ted Lyngmo Apr 07 '21 at 07:28
  • oh because I do not have enough reputation to vote :( Sadly – Hoa Trinh Apr 07 '21 at 07:30
  • I think I need to have at least 15 reputation or sth like that to up vote a question – Hoa Trinh Apr 07 '21 at 07:31
  • @HoaTrinh You do not need any reputation to _accept_ answers. Please read the link I shared in my comment. – Ted Lyngmo Apr 07 '21 at 08:56

0 Answers0