c - 我正在尝试用 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;
}
我只希望显示我的矩阵的最后一行。
解决方案
我猜你的意思是这样的。
请注意,作为字符串的“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.";
}
}
}
推荐阅读
- sql - 循环访问 Access SQL 中的列
- graph - 如何重新分配图形元素以最大化可读性?
- c# - 有没有办法在不指定类型参数的情况下访问嵌套在泛型类中的类?
- javascript - React 应用程序转换为 react-native - react-redux 和 react-thunk 的问题
- python - 在 Django Web 框架中使用 TMDb API 检索数据库中电影的海报
- swt - 填充 TableViewer 时文本字段丢失
- sql - 批量插入数据库,跳过数据库中发现的重复项
- asp.net - 提交表单后,我在控制器中收到空值
- python - PyCharm 上的 virualenv 从 Linux 到 Windows
- c++ - 在 VS2019 解决方案中包含 MRPT 库时出现错误 C2039