C 字符数组导致段错误

标签 c arrays pointers arguments stdio

我想让用户输入一系列我读作字符的行,并将其保存到一个数组中。我有一个效用函数,它应该打印网格中每个项目的值。但是,printMaze() 中使用 putchar() 的行导致了段错误,可能是因为 **maze 出了问题> 争论,虽然我不知道是什么原因造成的,也不知道如何解决。这是下面的代码。

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

void printMaze(char **maze, int width, int height){
    for (int x = 0; x < width; x++){
        for (int y = 0; y < height; y++){
            putchar(maze[x][y]);
        }
    }
}

int main(int argc, char *argv[]){
    int width, height;
    scanf("%d %d", &height, &width);
    char originalMaze[width][height];
    for (int y = 0; y < height; y++){
        for (int x = 0; x < width; x++){
            originalMaze[x][y] = getchar();
        }
        getchar();
    }
    printMaze(originalMaze, width, height);
    return 0;
}

最佳答案

void printMaze(char **maze, int width, int height)

正在寻找指向指针的指针,但您只提供了一个指针(原始迷宫)

printMaze(originalMaze, width, height);

您的编译器可能无论如何都会传递不兼容的类型并让程序启动,但是一旦您尝试将值加载到数组中它就不会工作。

关于C 字符数组导致段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40071585/

相关文章:

c - 通过 SPI 写入和读取闪存

c - 关于从 C 中的文本文件中读取 char 数组的任何建议?

c - 双向链表没有正确创建

arrays - 包含具有多个参数的 Twig

c++ - 在 C++ 中将对象作为参数传递给函数时修改的对象

c++ - 指向文字的指针?

c - 使用 dlopen 访问 POSIX 函数

c - execvp 出现段错误

c - 如何在 C 中找到 Unix system() 函数路径

在 C 中将字符数组转换为整数数组以进行 ISBN 验证