2
#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?

1
  • 1
    What's wrong with std::array and/or std::vector? C-style arrays seem "quaint" these days.. Commented Nov 14, 2019 at 19:17

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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.

2 Comments

makes sense, how does the compiler keep track of this information for the array pointer? since it doesn't throw segmentation fault
@RohithYeravothula I'm sorry. I have not understood the question.
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.