D
D
dandropov952018-09-18 00:07:27
C++ / C#
dandropov95, 2018-09-18 00:07:27

How to deal with a pointer to a pointer to an array?

What happens in this case int ** ptr = &arr;? It turns out that next ptr == arr == &arr. Why is it impossible to get a pointer to a pointer to an array in this case?
How will a pointer to a pointer look like schematically if it is assigned the address of the element, and not the address of the pointer? In this case, it turns out that it will be possible to get the value by a single dereference, and with a double one, a segmentation error is obtained.

#include <stdio.h>

int main(void)
{
  int arr[4] = {1, 2, 3, 4};
  int ** ptr = &arr;
  
  int value = 12;
  int * value_ptr = &value;
  int ** value_ptr_ptr = &value_ptr;
  
  printf("%d\n", **value_ptr_ptr); // 12

  printf("%d", *ptr); // 1
  // printf("%d", **ptr); // error

  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2018-09-18
@jcmvbkbc

What happens in this case
int ** ptr = &arr;

Happens initialization from incompatible pointer type.
Because to get a pointer to a pointer, you need to have this second pointer. An array is not a pointer.
This is how it will work:
#include <stdio.h>

int main(void)
{
  int arr[4] = {1, 2, 3, 4};
  int *pa = arr;
  int ** ptr = &pa;

  printf("%d", **ptr); // 1
  return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question