Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them, it only takes a minute:

I want to make a function which takes an existing 9x9 empty array of integers, and inserts values taken from a file (so the function also gets the file name as input). But I cant really figure out how to do this properly, even though I've tried quite a few different methods. Basically, here is what I do:

int board = new int[9][9] //The empty array

int addToArray(int *board, string filename) {

    /* Code to insert values in each field is tested and works so 
       I will just show a quick example. The below is NOT the full code */
    int someValue = 5;
    board[0][0]   = someValue;

    /* Return a value depending on whether or not it succeeds. The variable 'succes'
       is defined in the full code */
    if (succes) {
        return 0;
    } else {
        return -1;
    }
}

This is a very reduced example, compared to the actual code, but it is overall function of passing a pointer to a an array into some function, and have that function modifying the array, that I want. Can anyone tell me how to do this?

share|improve this question
1  
Souldn't your function prototype be : int addToArray(int **board, string filename) since you have an array of array ? – Elfayer Jul 21 '14 at 14:11
1  
passing 2D array to function – Johnny Mopp Jul 21 '14 at 14:13
    
I will test it when I get the time, but I think you guys are on to something. Never worked with 2D arrays in C++ before, so I am slightly confused :-). – Noceo Jul 21 '14 at 15:42
    
You should use C++ STL containers. – Basile Starynkevitch Jul 24 '14 at 7:25

2 Answers 2

up vote 0 down vote accepted

In case anyone ever ends reading the question, I used method number 3 from Johnny's link. I copy pasted the code and added some comments, for convenience...

// Make an empty, and un-sized, array
int **array;

// Make the arrays 9 long
array = new int *[9];

// For each of the 9 arrays, make a new array of length 9, resulting in a 9x9 array.
for(int i = 0; i < 9; i++)
    array[i] = new int[9];

// The function to modify the array
void addToArray(int **a)
{
    // Function code. Note that ** is not used when calling array[][] in here.
}
passFunc(array); 
share|improve this answer

It should be simply

int **board

in the function arguments.

The simple rule is that *name = name[ ], so as many [ ] you have in the array, you need to have as many * in the parameters.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.