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

Ear*_*rlz 8 c pointers casting segmentation-fault

好吧我的C有点生疏,但我想我会在C中制作我的下一个(小)项目,所以我可以对它进行修改,不到20行,我已经有了一个seg错误.

这是我的完整代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我完全混淆了这是如何导致段错误的.从铸造[][]到发生时会发生什么**?这是我得到的唯一警告.

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

[][]**真的不兼容的指针类型?他们似乎只是我的语法.

ken*_*ytm 36

A char[ROWS][COLS+1]不能投入char**.输入参数print_map应该是

void print_map(char map[][COLS+1])
Run Code Online (Sandbox Code Playgroud)

要么

void print_map(char (*map)[COLS+1])
Run Code Online (Sandbox Code Playgroud)

不同之处在于char**指向可以像这样解除引用的东西的方法:

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

而a char(*)[n]是指这样的连续记忆区域

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

如果你把a (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
Run Code Online (Sandbox Code Playgroud)

  • +1为可爱的ascii-art和指向数组的指针. (6认同)