-1

I'm trying to get this simple c++ program to work but I keep bouncing from error to error.
Here's the code:

#include <iostream>
using namespace std;

const int row = 3;
const int col = 3;
int array[row][col];

void print(int array[row][col]){
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            cout << array[i][j];
        }
    }
}

void setValues(int (&array), int value){
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            array[i][j] = value; //invalid types 'int[int]' for array subscript
        }
    }
}

int main() {
    setValues(array, 30); //Expected primary-expression before ',' token + Invalid Arguments 'Candidates are: void setValue(int &, int)
    print(array); //expected primary=expression before ')' token
    return 0;
}

I want to change values in a 2D array with a function.

user74096
  • 11
  • 1
  • 7

1 Answers1

0
typedef int array[row][col];

What you are doing here is creating an alias for int that's called array[row][col]. Just remove the typedef and it will work just fine.

Edit: Forgot about the other error

void setValues(int (&array)[row][col], int value)

It also works like this

void setValues(int array[row][col], int value)
Catalin
  • 474
  • 4
  • 19
  • Removed the typedef but the errors are still there. – user74096 Sep 04 '15 at 10:22
  • @user74096 by removing the `&` you completely go around what the question is about. The new version of setValues() suggested by Catalin uses pass by value and not pass by reference. See http://stackoverflow.com/a/5724184/1559401 for more information. Also if the array variable is declared as it is right now (that is - its scope is global) you don't need to bother passing it to a function as a parameter at all since it is perfectly visible inside the function's body due to its scope. – rbaleksandar Sep 04 '15 at 10:39
  • @rbaleksandar I don't understand what you're referring too. The corrected version of the code is `void setValues(int (&array)[row][col], int value)` is that not call by reference? – user74096 Sep 04 '15 at 14:45
  • @user74096 I was actually referring to `void setValues(int array[row][col], int value)` which is given as alternative by Catalin and is call by value and not by reference unlike the one you have pointed in your comment. – rbaleksandar Sep 04 '15 at 16:07
  • @rbaleksandar There's no such thing as call by value with arrays. – Catalin Sep 04 '15 at 18:08
  • My bad. I'm so used to using `*` and `&` that `int array[][]` has started to look alien to me. LOL – rbaleksandar Sep 04 '15 at 18:55