Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code print addresses?

Why didn't I get a compile time error while accidentally printing only one dimension of a 2D array?

#include <stdio.h>

void main() {
    int i;
    int arr[2][3] = { 1, 2, 3, 4, 5, 6 }; //<- Declared a 2D array

    for (i = 0; i < 6; i++) {
        printf("%d\n", arr[i]);  // <- Accidently forgot a dimension
    }
}

I should have received a compile time error but instead I got a group of addresses! Why? What did arr[0] mean in this context to the compiler?

like image 260
Kunal B Avatar asked Dec 05 '25 09:12

Kunal B


1 Answers

An expression with array type evaluates to a pointer to the first array element in most contexts (a notable exception, among others, is the sizeof operator).

In your example, arr[i] has array type. So it evaluates to a pointer of type int (*)[] (a pointer to an array). That's what's getting printed. Printing a pointer with %d is undefined behavior, because printf() will read the pointer as if it was an int.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!