简体   繁体   English

分段故障 - malloc 二维阵列

[英]Segmentation Fault - malloc 2D array

Trying to create a map for a little game.试图为一个小游戏创建一个 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. 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. Totally lost at why this isn't working.完全不知道为什么这不起作用。 Any help appreciated.任何帮助表示赞赏。

This is work for University, who insist the code is in C89 and I compile with -ansi -pedantic -Wall -Werror.这是大学的工作,他们坚持代码在 C89 中,我使用 -ansi -pedantic -Wall -Werror 进行编译。

GAME.C file 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 file 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;

}

The function createMap is incorrectly initializing objects of the type char with pointers of the type char * to which the string literal "0" is implicitly converted in these for loops function createMap使用char *类型的指针错误地初始化char类型的对象,在这些 for 循环中将字符串文字"0"隐式转换为该指针

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

Instead of the string literal you need to use integer character constant '0' as for example例如,您需要使用 integer 字符常量'0'而不是字符串文字

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

Another problem is a typo in this loop within the function printMap另一个问题是 function printMap中此循环中的错字

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

You need to write你需要写

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

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

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