C - 正在使用该变量而未进行初始化

时间:2015-05-07 20:07:10

标签: c++ c conways-game-of-life

我是C/C++编程语言的新手。我想使用C programming language制作简单的 Conway's Game of Life

我的代码如下所示:

#include "stdafx.h"

// Define some constants
const int DIM = 10;
int board[DIM][DIM];

int checkNeighbours(int x, int y) {
    int left, right, top, bottom = 0;
    int sum;

    // Check neighbour cells
    if (board[x - 1][y]) { left = 1; }
    if (board[x + 1][y]) { right = 1; }
    if (board[x][y - 1]) { top = 1; }
    if (board[x][y + 1]) { bottom = 1; }

    sum = left + right + top + bottom;

    return sum;
}

// Build a board
void buildBoard() {
    int i, j, neighbour_count;

    for (i = 0; i < DIM; i++) {
        for (j = 0; j < DIM; j++){

            neighbour_count = checkNeighbours(i, j);

            // Underpopulation
            if (neighbour_count < 2) { board[i][j] = 0; }
            // Lives if nc is 2 or 3
            // Overpopulation
            if (neighbour_count > 3) {
                board[i][j] = 0;
            }

            // Revive 
            if (neighbour_count == 3) {
                board[i][j] = 1;
            }
        }
    }

    // Predefined board cells
    board[1][2] = 1;
    board[1][3] = 1;
    board[2][2] = 1;
}

void drawBoard() {
    int i, j;

    for (i = 0; i < DIM; i++) {
        for (j = 0; j < DIM; j++) {
            char figure= (board[i][j]) ? 'A' : '_';
            printf("%c", figure);
        }
        printf("\n");
    }
}

int main()
{
    buildBoard();
    drawBoard();

    getchar();
    return 0;
}

错误我得到了:

Run-Time Check Failure #3 - The variable 'left' is being used without being initialized.

Run-Time Check Failure #3 - The variable 'right' is being used without being initialized.

Run-Time Check Failure #3 - The variable 'top' is being used without being initialized.

我如何解决这个问题,因为我已经初始化了这些变量。

1 个答案:

答案 0 :(得分:12)

int left, right, top, bottom = 0; 

仅初始化最后一个变量。更好:

int left = 0 , right = 0, top = 0, bottom = 0;

int left, right, top, bottom;
left = right = top = bottom = 0;

相同的味道:

char* a, b, c, d; 

仅将a声明为char*指针,其余bcd均为char