2d Array in function?

I've only been coding for a week in a half now. I recently decided the best way to learn would be to set my own goals and work on them. I'm currently working on a game where I use a char array to hold my map. I plan on updating this to a .txt file in the future.

The real problem at hand is how could I set the 2d array gameMap as a function parameter?

1
2
3
4
5
6
7
8
9
  void checkKey()
{
	for (int y = 0; y < 40; y++)
	{
		//find player character piece
		for (int x = 0; x < 40; x++)
		{
		if (gameMap[y][x] == '@')
			{ //code here } 


My obvious goal is to make my code reusable using function paramters

Edit: I believe I have figured it out. I kept attempting to call the array with '[]' such as
 
checkKey(Map[][40]);



Last edited on
This is how you pass a 2D array to a function.

1
2
3
4
5
6
int array[10][10];
void passFunc(int a[][10])
{
    // ...
}
passFunc(array);


Note that you should write the number of columns.

Also, if you want to pass a 2D array to a function, you just pass its name without [][], like in line 6.
Last edited on
If you want to pass it in as a parameter with it being just a character array of size 40 * 40,
it would look something like this.
1
2
3
4
5
6
7
void foo(char arr[][40], int size){
    for(int i = 0; i < size; i++){
        for(int j = 0; j < size; j++{
            // or something like this.
        }
    }
}


You have to know the size of the array when declaring the function header. That [40] is there or else it won't compile.
Otherwise you would probably have to create a dynamic 2D array of pointers. char** arr then dynamically allocate it. Hope this helps.
Topic archived. No new replies allowed.