铸造的char [] []到char **导致段错误? [英] casting char[][] to char** causes segfault?
问题描述
好吧我的C是有点生疏,但我想我会做用C我的下一个(小)的项目,所以我可以擦亮备份就可以了不到20行的我已经有一个赛格故障。
Ok my C is a bit rusty but I figured I'd make my next(small) project in C so I could polish back up on it and less than 20 lines in I already have a seg fault.
这是我的完整code:
This is my complete code:
#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;
}
我来这是如何造成段错误完全糊涂了。从 [] []
铸造时发生了什么**
!?这是唯一的警告,我得到。
I am completely confused as to how this is causing a segfault. What is happening when casting from [][]
to **
!? That is the only warning I get.
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]’
是 [] []
和 **
真的不兼容的指针类型?他们看起来他们只是语法我。
Are [][]
and **
really not compatible pointer types? They seem like they are just syntax to me.
推荐答案
A 的char [行数] [COLS + 1]
不能转换成字符**
。 print_map
的输入参数应该是
A char[ROWS][COLS+1]
cannot be cast into a char**
. The input argument of print_map
should be
void print_map(char map[][COLS+1])
或
void print_map(char (*map)[COLS+1])
区别在于一个的char **
表示为指向的东西,可以解除引用如下:
The difference being that a char**
means to point to something that can be dereferenced like this:
(char**)map
|
v
+--------+--------+------+--------+-- ...
| 0x1200 | 0x1238 | NULL | 0x1200 |
+----|---+----|---+--|---+----|---+-- ...
v | = |
+-------+ | |
| "foo" | <-----------------'
+-------+ |
v
+---------------+
| "hello world" |
+---------------+
而在字符(*)[N]
是一个点,这样的连续内存区域
While a char(*)[n]
is a points to a continuous memory region like this
(char(*)[5])map
|
v
+-----------+---------+---------+-------------+-- ...
| "foo\0\0" | "hello" | " worl" | "d\0\0\0\0" |
+-----------+---------+---------+-------------+-- ...
如果你把一个(CHAR(*)[5])
为(字符**)
你让垃圾:
If you treat a (char(*)[5])
as a (char**)
you get garbage:
(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 **导致段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!