Ayush Shrivastava Ayush Shrivastava - 4 months ago 13
C Question

Why does this simple C code print the addresses in the reverse order ? (For Ex. 4214868 4214864)

Prints the addresses of

i
and
j
.

#include<stdio.h>
int i,j;
void main()
{
printf("%u %u",&i,&j);
getch();
}





Output:

4214868 4214864

Answer
#include<stdio.h>
int i,j;
void main()

This is wrong. (That's a slight oversimplification, but it's close enough.) The correct declaration is int main(void).

{
    printf("%u %u",&i,&j); 

The "%u" format requires an argument of type unsigned int. Passing an int* pointer value causes undefined behavior. The correct way to print the addresses is:

printf("%p %p\n", (void*)&i, (void*)&j);

Note the \n: a program's output should end with a newline.

    getch();

There is no getch() function declared in <stdio.h>. If you didn't get at least a warning on that call, you should find out how to enable better diagnostics in your compiler.

You're probably trying to call the getch() function declared in the Windows (and DOS?) specific <conio.h> header. This makes your program unnecessarily non-portable.

}

As for the values it's printing, the C standard says nothing about the relative addresses of variables. The compiler is free to allocate them in any way it likes. And there's no good reason for you to care whether i is allocated before or after j in memory.