[英]Segmentation Fault From Using 2D Array in Function (probably)
Edit3:添加了示例。
Edit2:所以,因為我是一般的編碼新手,並且由於當前的評論,我需要問,如果我將整個代碼作為評論發布會更好嗎? (約 90 行)
所以,我一直在玩動態 memory 分配,我有一個 2D 板,巫婆用“。”填充。 然后我將電路板導入 function 中,檢查可用單元格(帶有'.'==available 的單元格)。 它可以編譯,但是當我運行它時,我得到了
segmentation fault
這是板 malloc 的代碼
**board = (char**) malloc(x_input*sizeof(char*));
for(i = 0; i <x_input; i++){
board[i] = (char*) malloc(y_input*sizeof(char));
}
for (i = 0; i<x_input; i++){
for(j = 0; j<y_input; j++){
board[i][j]='.';
}
}
這是 Function
int checker(int x_axis, int y_axis, char **board){
if (board[x_axis][y_axis] == '.'){
return 1;
} else {
return 2;
}
}
這是我唯一一次(到目前為止)調用 function 編輯: x_replacement
和y_replacement
通過 rand function
do{
board[x_replacement][y_replacement] = '$';
} while(checker(x_replacement, y_replacement, board) == 2);
前任:
const int MAX_X = 40;
const int MAX_Y = 40;
const int MIN_X = 20;
const int MIN_Y = 20;
int x_input, y_input;
int main(void){
char **board;
int i, j, k, obstacles, enemies, choice;
do{
printf("Enter board size. (Must be between (%d, %d) and (%d, %d))\n:", MIN_X, MIN_Y, MAX_X, MAX_Y);
scanf("%d%d", &x_input, &y_input);
}while ((x_input <= MIN_X && x_input >= MAX_X) && (y_input <= MIN_Y && y_input >= MAX_Y));
*board = malloc(sizeof(char[x_input][y_input]));
assert(*board != NULL);
for (i = 0; i<x_input; i++){
for(j = 0; j<y_input; j++){
board[i][j]='.';
}
}
return 0;
}
由於 Ludin 和 Some Programmer Dude 的鏈接,我從不同的角度處理了這個問題,所以結果,女巫的工作如下:
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
void arr_alloc (size_t x, size_t y, char(**board)[x][y])
{
*board= malloc( sizeof(char[x][y]) );
assert(*board!= NULL);
}
void arr_fill (size_t x, size_t y, char board[x][y])
{
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
array[i][j] = '.';
}
}
}
void arr_print (size_t x, size_t y, char board[x][y])
{
for(size_t i=0; i<x; i++)
{
for(size_t j=0; j<y; j++)
{
printf("%c ", board[i][j]);
}
printf("\n");
}
}
int main (void)
{
int x,y;
char (*board)[x][y];
printf("enter dimentions: \n");
scanf("%d%d", &x, &y);
arr_alloc(x, y, &board);
arr_fill(x, y, *board);
arr_print(x, y, *board);
free(board);
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.