简体   繁体   中英

Dereferencing a Two Dimensional Array In C

I'm having some difficulties understanding two dimensional arrays in C.
Let's look at this example:

#include <stdio.h>

void foo(int arr[2][3]) {
    printf("%d", *arr); 
}

int main() {
    int arr[2][3] = {   {10, 20, 30}, 
                        {40, 50, 60}
                    };
    foo(arr);
    return 0;
}


I have a few questions:

  1. What is the value of arr ? Is it the address of arr[0][0]?
  2. If arr is the address of arr[0][0], then why the line:
    printf("%d", *arr);
    doesn't print the value 10?
  3. Each time I run it, I get a strange number. what is the meaning of this number?

Thanks:)

In answer to your questions:

  1. Used in an expression, the value of arr is a pointer to its first element. Since it's an array of arrays, the pointer to its first element is &arr[0] . This value has an unusual type, "pointer to array of 3 ints".

  2. Because arr is not the address of arr[0][0] .

  3. This is a crazy situation, hard to understand and hard to explain. In brief: since arr is a pointer to an array, *arr is that array. But when you try to pass it to printf , the compiler turns around and generates a pointer to the array's first element again. I suspect that pointer value differs because your compiler and OS are putting main (and therefore arr ) in a different place on the stack each time. (And then there's the additional problem that since we're talking about pointers, it doesn't necessarily work to print them %d , especially if your machine has 32-bit ints and 64-bit pointers.)

My advice to you is not to worry about why the incorrect code printed changing values. Rather, please just print the array correctly, with code like this:

int i, j;
for(i = 0; i < 2; i++) {
    for(j = 0; j < 3; j++)
        printf("%d ", arr[i][j]);
    printf("\n");
}

It is possible by doing like this:

#include <stdio.h>
int main()
{

    int arr[2][2] = {{2,3},{5,6}};

    for (int i = 0; i < 2; i++) {

        for (int j = 0;j < 2; j++) {

            printf("%d\n" , *(&arr[i][j]));
        }
    }
}

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