简体   繁体   中英

%u format Specifier in C

I compiled this code and it gave the the value of '&x' 3 times. That is if &x = 2000 it printed 2036 three times. I want to know the reason for this behaviour assuming an integer requires 4 bytes of memory.

#include <stdio.h>
int main(void) {
    // your code goes here
    int x[4][3] = {0};
    printf("%u %u %u", x+3, *(x+3), *(x+2)+3);
    return 0;
}

What will be the output of this code

Anything can happen as the code provokes undefined behaviour by printing a pointer value using the conversion specifier for an unsigned .

To print pointer values use the conversion specifier p .


The address of an array and the address of its 1st element are the same. Pointers to them both however are of different type.


x as well as x + 3 are of type int (*)[3] , that is pointing to an array of three int s. Assuming int to be of size 4 , an array of three int s is of size 12 .

Increasing x (a pointer to int (*)[3] ) by three elements one ends up with an address 3 * 12 bytes beyond where x points to. This is called pointer arithmetic.

You're misusing a format specifier and invoking undefined behavior because of that. At that point, what happens is arbitrary and uninteresting.

If you want to print a pointer, use the %p specifier.

x is a pointer to an array of pointers. The array of pointers has 4 elements. Each of these four elements points to 3 integers.

Hence if x = 2000 then,

x[0] = 2000, x[1] = 2012, x[2] = 2024, x[3] = 2036.

Therefore,

x + 3 = 2036 (because x is an array pointer and it increases by 12 each time.)

*(x+3) = x[3] = 2036 again.

*(x+2)+3 = x[2] + 3 = 2024 + 3*4 = 2036 again.

Hence the output will be three same numbers.

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