繁体   English   中英

分段故障 - malloc 二维阵列

[英]Segmentation Fault - malloc 2D array

试图为一个小游戏创建一个 map。 When initialising the map with 2D arrays using malloc, the main function will run okay when the printMap function is commented out, however when trying to display the map with printMap, it returns a Segmentation fault. 完全不知道为什么这不起作用。 任何帮助表示赞赏。

这是大学的工作,他们坚持代码在 C89 中,我使用 -ansi -pedantic -Wall -Werror 进行编译。

GAME.C 文件

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include"random.h"

void createMap(char*** map, int xCoord, int yCoord) {
    int i, j;
    xCoord += 2;
    yCoord += 2;
    char** mapArray;

    mapArray = (char**)malloc(yCoord * sizeof(char*));
    for (i = 0; i < yCoord; i++) {
        mapArray[i] = (char*)malloc(xCoord * sizeof(char));
    }
    for (i = 0; i < yCoord; i++) {
        for (j = 0; j < xCoord; j++) {
            mapArray[i][j] = "0";
        }
    }
    *map = mapArray;
}

void printMap(char** map, int xCoord, int yCoord) {
    xCoord += 2;
    yCoord += 2;
    printf("%d, %d", xCoord, yCoord);
    int i, j;
    
    for (i = 0; i < yCoord; i++) {
        for (j = 0; j < xCoord; i++) {
            printf("%d %d", i, j);
            printf("%c", map[i][j]);
        }
        printf("\n");
    }
}

MAIN.C 文件

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include "random.h"
#include "game.h"

int main(void) {
    int xCoord = 5;
    int yCoord = 5;

    char** map;

    createMap(&map, xCoord, yCoord);
    
    printMap(map, xCoord, yCoord);
    return 0;

}

function createMap使用char *类型的指针错误地初始化char类型的对象,在这些 for 循环中将字符串文字"0"隐式转换为该指针

for (i = 0; i < yCoord; i++) {
    for (j = 0; j < xCoord; j++) {
        mapArray[i][j] = "0";
    }
}

例如,您需要使用 integer 字符常量'0'而不是字符串文字

for (i = 0; i < yCoord; i++) {
    for (j = 0; j < xCoord; j++) {
        mapArray[i][j] = '0';
    }
}

另一个问题是 function printMap中此循环中的错字

for (j = 0; j < xCoord; i++) {
                        ^^^^

你需要写

for (j = 0; j < xCoord; j++) {
                        ^^^^

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM