Jugesh Sundram
Jugesh Sundram

Reputation: 273

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

Upvotes: 0

Views: 572

Answers (3)

Victor Chavauty
Victor Chavauty

Reputation: 184

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

Upvotes: 0

bobestm
bobestm

Reputation: 1334

You are indexing Board[2][2] in init_board() you are indexing out-of-bound of the specified size of the array i.e. 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.

Upvotes: 0

Vikdor
Vikdor

Reputation: 24124

The initializer syntax can be used only while declaring the array, i.e.

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

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

Upvotes: 2

Related Questions