I wrote the below code and when I try to compile it I get the following error:
error C2109: subscript requires array or pointer type.
Can anyone tell me what I did wrong and how I can fix it? Thanks a lot! :)

// This program writes the bombsweeper game. It uses a two-dimensional array that is 5x5 that is initialized
// at 0. 5 different pairs of random #s are generated (x,y) where a 1 at the location indicates a bomb. User 
// will input pairs to try to guess locations of the bombs for up to 7 guesses and at the end of the game
// the location of the bombs will be displayed. User can repeat as many times as they want.

#include "stdafx.h"
#include <ctime>
#include <cstdlib>
#include <iostream>
using namespace std;

void userGuess(int bs[]);

int main()
{
	srand((unsigned)time(NULL)); // seed random # generator

	int bs[5][5] = {0}; // declare & initialize array

	// loop for 5 random sets of #s
	for (int j = 0; j < 5; j++) 
	{
		int rn1 = rand() % 5; // random#1
		int rn2 = rand() % 5; // random#2

		bs[rn1][rn2] = bs[rn1][rn2] + 1; // put bomb in random location
	} // for

	void userGuess(int bs[]);
	
	cout << bs[5][5];

	return 0;
}

void userGuess(int bs[])
{
	// loop for 7 guesses
	for (int i = 0; i < 7; i++)
	{
		// get user location guess
		int x, y;
		cout << "Enter your guess of the location of a bomb: i.e. 3 4): ";
		cin >> x >> y;

		if (bs[x][y] == 1)
			cout << "Good Job, you got one!" << endl;
		else 
			cout << "Sorry, no bomb there. Try Again." << endl;
	} // for
} // userGuess

Edited 7 Years Ago by mz_rigel: n/a

When a one-dimensional array is defined as a formal parameter,
the side of the array may be omitted.

void test(int args[]) { 
. . . 
}

With two-dimensional arrays, the first dimension may be omitted,
but not the second dimension.

void test(int args[][3]) { 
. . . 
}

You can specify both dimensions if you choose to.

void test(int args[2][3]) { 
. . . 
}

C++ doesn't care about bounds, but it needs to compute the memory address given the subscripts. To do this it needs to know the row width (number of columns). Therefore formal 2-dimensional array parameters must be declared with the row size, altho the number of rows may be omitted.

Edited 7 Years Ago by __avd: n/a

This article has been dead for over six months. Start a new discussion instead.