The difference between a pointer to a pointer and a pointer to a 2d array

  • If I have a 2d array of B defined as:

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

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

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

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

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

    returns a segmentation error! Why?

+1
c pointers multidimensional-array pointer-to-pointer
Aug 01 '14 at 12:35 on
source share
2 answers
  • No. int **p = B; - mistake. (Both a compilation error and a logical error). int ** must point to int * . However, there is no int * in B B is a group of contiguous int without pointers.

  • int **f = B; should give a compilation error. The behavior of any executable file generated as a result is completely undefined.

  • See 2.




To explain why you can see 1 and 5 . (The C standard does not define this, but your bull compiler is ahead in any case). Your compiler probably treats the line as

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

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

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

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

When dereferencing this pointer, it calls segfault because this address is outside the valid address space.

+2
Aug 01 '14 at 12:39 on
source share
β€” -

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

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

2) int **f = B; This is a mistake, May leads to Undefined behavior!

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

NOTE. To avoid this type of error, enable some warning flags in the compiler options and try!

+1
Aug 01 '14 at 12:45
source share



All Articles