Difference between pointer to pointer and pointer to 2d array

坚强是说给别人听的谎言 提交于 2019-12-14 03:42:31

问题


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

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

    Is int **p = B same as int (*p)[3] = B ?

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

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

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

    returns a segmentation fault! Why?


回答1:


  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.

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

  3. See 2.


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;

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.

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 *.

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.




回答2:


1) Is int **p = b same as int (*p)[3] = b ? - No. int **p = b is an error.

Because here int **p is a pointer to pointer to an integer, but int (*p)[3] is pointer to an array of 3 integers!

2) int **f = B; It is an error, May results in Undefined behavior!

3) printf("%d ",**f); - It is same as (2). int **f = B; is error, so Undefined behavior!

NOTE: To avoid this type of error enable some warning flags in compiler option and try!



来源:https://stackoverflow.com/questions/25080413/difference-between-pointer-to-pointer-and-pointer-to-2d-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!