简体   繁体   中英

Accessing Global Variable in function c++

I have a very basic doubt. From the code below , I have declared Board[ ][ ] as a global char array. I would like to initialize the array in a function called init_board() . But the compiler returns

In function void init_board():
expected primary-expression before '{' token
expected ;' before '{' token

Code:

#include <iostream>
#include <conio.h>

using namespace std;

//global variables---------------
char Board[2][2];

//function declarations----------
void init_board();

int main(void)
{
init_board();

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

getch();
}

void init_board()
{
Board[2][2] = {{'a','b'},{'c','d'}}; 
}

What is the basic error I am making...please point out !!

Thanks

The initializer syntax can be used only while declaring the array, ie

char board[2][2] = {{'a', 'b'}, {'c', 'd'}};

In all other cases, you need to browse through the array elements and set them.

You are indexing Board[2][2] in init_board() you are indexing out-of-bound of the specified size of the array ie you have specified that the array is 2 rows and 2 columns but you are indexing into element 3 (indexing starts at 0 in C/C++ and a few other languages). You can initialise the array at compile time at the top of the file where you have declared it:

char Board[2][2] = {{'a','b'},{'c','d'}}; 

Or you can initialise each element individually as others have suggested.

void init_board()
{
Board = {{'a','b'},{'c','d'}};
}

That sould fix it... When you use Board[2][2] you are only reffering to the one char in the position [2][2]. So that means you would be adding a, b, c and d to only one bite of the Board

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM