Reputation: 435
#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?
Upvotes: 2
Views: 130
Reputation: 93
I rewrote the code to highlight what is happening, as below:
#include <iostream>
int main() {
int a[2][2] = {{1,2}, {3,4}};
int *c[2] = {a[0], a[1]};
int **b = c;
std::cout << **(a ) << ','; // outputs 1
std::cout << **(b ) << ";\n"; // outputs 1
std::cout << **(a+1) << ','; // outputs 3
std::cout << **(b+1) << ";\n"; // outputs 3
}
LINK: https://ideone.com/ixj3NV
UPDATED LINK: https://ideone.com/g7jjVN (Clarified the original source to extend the program)
Upvotes: 0
Reputation: 310970
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.
Upvotes: 3
Reputation: 122450
Lets start with
int *c;
Actually what comes before is not that relevant, because c
is just a pointer and then here
int **b = &c;
you store the address of c
in b
. The address of c
has nothing to do with what value is stored in c
. c
is just a pointer, taking its adress doesn't let you magically access a 2d array.
cout << **(b+1); // segmentation fault
Already b+1
is undefined behaviour. Dereferencing that pointer cannot give you something meaningful.
PS: tbh I cannot tell you how to use the double pointers correctly here. Once I started to learn c++ I unlearned anything I knew about working with arrays via pointers. Use std::vector
or std::array
and save yourself some headaces.
Upvotes: 4