tags:

views:

184

answers:

5
void main(){
    int i,k;
    char* p;
    int j;
    printf("address of i is %d \naddress of k is %d \naddress of p is %p\naddress of j is %d", &i,&k,&p,&j);

}

when I tried the above code, the address of j is 4 units below k. But the address of p is no where near. Since a pointer is an integer variable that could store 4 bytes of data, why isn't it allocated on the stack like the other three variables?

+10  A: 

Use %p to print all the addresses.

Spoiler: It is on the stack.

Michael Foukarakis
+9  A: 

You should post the output you're getting. I suspect that you're getting a bit confused because most of the addresses you're printing are being displayed in decimal (using %d) while p is being displayed in hex (using %p).

Michael Burr
+6  A: 

I just tried your code on my computer (running Ubuntu 9.04) and got the following:

address of i is 0xbf96fe30
address of k is 0xbf96fe2c
address of p is 0xbf96fe28
address of j is 0xbf96fe24

after changing the code somewhat:

void main(){
    int i,k;
    char* p;
    int j;
    printf("address of i is %p \naddress of k is %p \naddress of p is %p\naddress of j is %p\n", &i,&k,&p,&j);

}

Since all you're printf() are addresses you should use %p instead of %d. Maybe you misinterpreted your results?

Puppe
A: 

When you use %d printf() specifier you get an address printed as decimal number and when you use %p specifier you get it printed as hexadecimal number. It just happened that the hexadecimal number contains no letters and you misinterpret it.

sharptooth
A: 

Pointers may or may not be located on the stack as they are also some sort of variables. Note that they are some not very big variables. If the CPU/MCU has lots of registers and the compiler optimizes well, you may not see a pointer on the stack, it may very well spend its whole lifetime in registers.

Malkocoglu
Frank Bollack
@Frank: I was referring the question (the title itself), not the given code snippet...
Malkocoglu
Is it a sin to elaborate on questions :-)
Malkocoglu
@Malkocoglu: No it is not, but then you should somehow make clear, that your answer doesn't reference the OPs actual question. You should also consider, that your answer might lead the OP into a false direction when looking for a solution to his problem.
Frank Bollack