首页 > 解决方案 > 我正在尝试用 malloc 分配 um 字符串矩阵,但返回分段错误,发生了什么?

问题描述

我正在尝试分配一个字符串矩阵,但是,在最后一行 mt 代码返回分段错误,我该如何解决?

char **allocate(char ***map, int lin, int col){
    int index = lin;

    map = (char*** ) malloc(sizeof(char) * lin);

    for(int i = 0; i < index; i++){
        map[i] = (char**) malloc(sizeof(char) * col);
    }

    return (char**) map;
}

void **fill(char ***map, int index){

    printf("index: %d\n", index);

    for(int i = 0; i <index; ++i){
        for (int j = 0; j < index; ++j){
          map[i][j] = "aaaaaaaaa";
          printf("%s ", map[i][j]);
        }
        printf("\n");
    }

}



int main(){
    char **map = NULL;
    map = allocate(map,5,5);
    printf("\n");
    fill(map,5);
    return 0;
}

我只希望显示我的矩阵的最后一行。

标签: c

解决方案


我猜你的意思是这样的。

请注意,作为字符串的“const”是“const char *”而不是“char *”。

#include <malloc.h>
#include <stdio.h>

const char ***allocate(int lin, int col){
    int index = lin;

    const char ***map = (const char*** ) malloc(sizeof(char**) * lin);

    for(int i = 0; i < index; i++){
        map[i] = (const char**) malloc(sizeof(char*) * col);
    }

    return map;
}

void **fill(const char ***map, int index){

    printf("index: %d\n", index);

    for(int i = 0; i < index; ++i){
        for (int j = 0; j < index; ++j){
          map[i][j] = "aaaaaaaaa";
          printf("%s ", map[i][j]);
        }
        printf("\n");
    }

}



int main(){
    const char ***map = allocate(5,5);
    printf("\n");
    fill(map,5);
    return 0;
}

多次调用 malloc 并具有如此高的间接级别会导致编码效率非常低。

在这种情况下,创建一个 const char * 的常量 5x5 数组就足够了

int main() {
  const char *map[5][5];
  for (int i = 0; i != 5; ++i) {
    for (int j = 0; j != 5; ++j) {
      map[i][j] = "I should write my own assignment.";
    }
  }
}

推荐阅读