指向指针和指向2D数组的指针之间的区别 [英] Difference between pointer to pointer and pointer to 2d array

查看:101
本文介绍了指向指针和指向2D数组的指针之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 如果我将二维数组B定义为:

  1. If I have a 2d array B defined as :

int B[2][3] = {{1,3,5},{2,4,6}};

int **p = B是否与int (*p)[3] = B相同?

int **f = B; printf("%d ",*f+1);

给出5作为输出,而printf("%d ",*f)给出1作为答案.为什么 发生了吗?

gives 5 as output while printf("%d ",*f) gives 1 as answer. Why is that happening?

printf("%d ",**f);

返回分段错误!为什么?

returns a segmentation fault! Why?

推荐答案

  1. 否. int **p = B;是错误. (既有编译错误,也有逻辑错误). int **必须指向int *.但是,B中没有存储任何int *. B是一组连续的int,不涉及指针.

  1. No. int **p = B; is an error. (Both a compilation error, and a logical error). An int ** must point to an int *. However, there are no int * stored in B. B is a group of contiguous ints with no pointers involved.

int **f = B;必须给出编译错误.结果生成的任何可执行文件的行为都是完全不确定的.

int **f = B; must give a compilation error. The behaviour of any executable generated as a result is completely undefined.

请参阅2.


解释为什么您可能会看到15. (C标准没有对此进行定义,但是您的编译器无论如何都会向前冲).可能是您的编译器将该行视为


To explain why you might be seeing 1 and 5. (The C standard does not define this, but your compiler bulls on ahead anyway). Probably your compiler treats the line as

int **f = (int **)B;

然后,表达式*f将从B的存储中读取字节(实际上保存int s),并假装这些是组成指针表示形式的字节.这是进一步的未定义行为(违反严格混叠规则).可能的结果是*f是指向地址0x00000001的指针.

Then the expression *f will read bytes from the storage of B (which actually hold ints) and pretend that those are the bytes that make up a pointer representation. This is further undefined behaviour (violation of strict-aliasing rules). Probably the result of this is that *f is a pointer to address 0x00000001.

然后使用%d打印指针,从而导致进一步的未定义行为.您会看到1,因为您的系统使用与传递int *相同的方法来将int传递给printf.

Then you print a pointer by using %d, causing further undefined behaviour. You see 1 because your system uses the same method for passing int to printf as it does to pass int *.

(int *)0x00000001上加1时,会得到(int *)0x00000005,因为递增指针意味着指向该类型的下一个元素.

When you add 1 to (int *)0x00000001, you get (int *)0x00000005, because incrementing a pointer means to point to the next element of that type.

取消引用此指针时,由于该地址在有效地址空间之外,因此会导致段错误.

When you dereference this pointer, it causes a segfault because that address is outside of your valid address space.

这篇关于指向指针和指向2D数组的指针之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆