为什么我收到写访问冲突异常

时间:2018-09-13 10:06:07

标签: c access-violation

我是C语言的新手,现在已经两次遇到此问题。

问题是尝试运行以下程序时出现访问冲突错误。 initialize_board()函数中引发了异常。我在特定行上发表了评论。

任何有更多经验的人的见解将不胜感激!

#include <stdio.h>
#include <stdlib.h>

/* global variables */
const int BOARD_SIZE = 3;
const char X = 'X';
const char O = 'O';
char** active_board;

//creates a square 2d array of size BOARD_SIZE
void create_board() {
    //ptrs to array of chars
    active_board = (char*)malloc(sizeof(char*)*BOARD_SIZE);
    for (int i = 0; i < BOARD_SIZE; i++) {
        active_board[i] = (char)malloc(sizeof(char) * BOARD_SIZE);
    }
}

//fills board with either char X or O
void initialize_board(char symbol) { //symbol:= X or O
    for (int i = 0; i < BOARD_SIZE; i++) {
        for (int j = 0; j < BOARD_SIZE; j++) {
            active_board[i][j] = symbol;// <---EXCEPTION THROWN HERE
        }
    }
}

int main() {
    create_board();
    initialize_board(X);

    return 0;
}`

1 个答案:

答案 0 :(得分:1)

问题是那些演员

active_board = (char*)malloc(sizeof(char*)*BOARD_SIZE); /* Must return `char **` */
for (int i = 0; i < BOARD_SIZE; i++) {
    active_board[i] = (char)malloc(sizeof(char) * BOARD_SIZE); /* Must return `char *` */
}

Don't cast malloc

active_board = malloc(sizeof(char*)*BOARD_SIZE);
for (int i = 0; i < BOARD_SIZE; i++) {
    active_board[i] = malloc(sizeof(char) * BOARD_SIZE);
}