Search code examples
c++pointersdereference

cpp double pointer vs 2 dimensional array pointer


#include <iostream>

int main() {
    int a[2][2] = {{1,2}, {3,4}};
    int *c = *a;
    int **b = &c;
    std::cout << **(a+1);  // outputs 3
    std::cout << **(b+1);  // segmentation fault
}

Why does one cout results in segmentation fault and other doesn't? Shouldn't they be referring to the same value?


Solution

  • In this statement

    cout << **(b+1);
    

    the expression b+1 points outside the array (that is more precisely outside the object c). You should write

    cout << *( *b + 2 );
    

    The dereferenced pointer b points to the pointer to the first element of the two-dimensional array. When adding to it the number of elements in the array of the type int[2] you will get the pointer to the first element of the second "row" of the two-dimensional array. Now you need again to dereference it to output the pointed value.