gpt4 book ai didi

将 char[][] 转换为 char** 会导致段错误?

转载 作者:太空狗 更新时间:2023-10-29 16:57:28 26 4
gpt4 key购买 nike

好吧,我的 C 语言有点生疏了,但我想我会用 C 语言做我的下一个(小)项目,这样我就可以对其进行润色,不到 20 行我已经有段错误了。

这是我的完整代码:

#define ROWS 4
#define COLS 4

char main_map[ROWS][COLS+1]={
"a.bb",
"a.c.",
"adc.",
".dc."};

void print_map(char** map){
int i;
for(i=0;i<ROWS;i++){
puts(map[i]); //segfault here
}
}



int main(){
print_map(main_map); //if I comment out this line it will work.
puts(main_map[3]);
return 0;
}

我完全不明白这是如何导致段错误的。从 [][] 转换为 ** 时发生了什么!?这是我得到的唯一警告。

rushhour.c:23:3: warning: passing argument 1 of ‘print_map’ from incompatible pointer typerushhour.c:13:7: note: expected ‘char **’ but argument is of type ‘char (*)[5]’

[][]** 真的不兼容指针类型吗?对我来说,它们似乎只是语法。

最佳答案

char[ROWS][COLS+1] 不能转换为 char**print_map 的输入参数应该是

void print_map(char map[][COLS+1])

void print_map(char (*map)[COLS+1])

区别在于 char** 意味着指向可以像这样取消引用的东西:

   (char**)map
|
v
+--------+--------+------+--------+-- ...
| 0x1200 | 0x1238 | NULL | 0x1200 |
+----|---+----|---+--|---+----|---+-- ...
v | = |
+-------+ | |
| "foo" | <-----------------'
+-------+ |
v
+---------------+
| "hello world" |
+---------------+

虽然 char(*)[n] 是一个指向连续内存区域的指针,就像这样

   (char(*)[5])map
|
v
+-----------+---------+---------+-------------+-- ...
| "foo\0\0" | "hello" | " worl" | "d\0\0\0\0" |
+-----------+---------+---------+-------------+-- ...

如果你把 (char(*)[5]) 当作 (char**) 你会得到垃圾:

   (char**)map
|
v
+-----------+---------+---------+-------------+-- ...
| "foo\0\0" | "hello" | " worl" | "d\0\0\0\0" |
+-----------+---------+---------+-------------+-- ...
force cast (char[5]) into (char*):
+----------+------------+------------+------------+-- ...
| 0x6f6f66 | 0x6c686500 | 0x77206f6c | 0x646c726f |
+----|-----+---------|--+------|-----+------|-----+-- ...
v | | |
+---------------+ | | v
| "hsd®yœâñ~22" | | | launch a missile
+---------------+ | |
v v
none of your process memory
SEGFAULT

关于将 char[][] 转换为 char** 会导致段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2895433/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com