简体   繁体   中英

Dereferencing pointer to entire array

I'm learning pointers to (entire) arrays in C.

Suppose I declare a 2d matrix of ints:

int arr[3][3] = 
    {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

Now, I declare a pointer of appropriate type:

int (*ptr)[3][3];

Initialize it:

ptr = &arr;

Now, ptr contains the address of arr.

  ptr --->&(arr[0][0]   arr[0][1]   arr[0][2]
            arr[1][0]   arr[1][1]   arr[1][2]
            arr[2][0]   arr[2][1]   arr[2][2])

So, when we dereference ptr, it should yield the first location, isn't it?

printf("%d", *ptr) gives an error at compile time. To print the first element, I've to use ***ptr .

I have 2 questions:

  1. I can't understand the need for a triple dereferencing.
  2. If *ptr doesn't point to first element of array, what does it point to?
printf(*ptr);

is wrong since the first argument to printf needs to be a string that specifies the format to use to print the rest of the arguments. To print the address, use:

printf("%p", *ptr);

I can't understand the need for a triple dereferencing.

The type of p is int (*)[3][3] .

The type of *p is int [3][3] .

The type of **p is int [3]

The type of ***p is int .

When you have a pointer like that, it's best to use the array syntax.

(*p)[0][0]

The generic form would be:

(*p)[i][j]

That is a lot less confusing than using ***p . Besides, ***p can be used to access the [0][0]-th element of the array only.

If *ptr doesn't point to first element of array, what does it point to?

Hopefully the answer to the previous question explains this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM