简体   繁体   中英

What does int *p = (int*) 60 mean?

#include <stdio.h>

int main()
{
    int *p = (int*) 60;    --- Line 1
    int *q = (int*) 40;    --- Line 2
    printf("%d", p-q);    //Output is 5
    return 0;
}

Could anybody please explain to me the output of this program?

It means the (implementation-defined) action of assigning an integral value to a pointer happens. This often means that p points to the memory address at 60 and q to the address at 40 . These memory addresses could be in virtual memory, hardware memory, and many implementations have different conversion routines for these.

Since this is implementation-defined anything could happen, as described by your implementation.

But isn't this entirely worthless?

It's most certainly not, it is used a lot in embedded hardware programming to access certain features or call built-in functions.


Most likely on your system int is 4 bytes wide, so p - q equals (60 - 40) / 4 == 5 .

It's making p point to the memory address 60 and q point to the memory address 40 . Then presumably your architecture has 4-byte int s and so p - q equals 5 ((60 - 40) / 4).

You're creating two pointer values and then doing pointer math. Apparently sizeof(int) on your system is 4 bytes, so the distance between the two pointer values is 5.

Each pointer, p and q , is a pointer to an int. p points to memory address 60, and q to memory address 40. When you subtract q from p , the result is how many 4-byte int s fit in-between, in this case 5. that is done to make using pointers with arrays easier, if they were in the same array.

See this site for more information about pointer arithmetic.

The statement declares a pointer to an integer at address 60

int *p = (int*) 60;  

You probably already know this; The danger of doing this is: how do you know there is actually an integer stored at address 60?

The int pointer initialization is to ensure that the pointer is pointing to the memory address of an integer, in this case memory location 60 and 40 for pointers p and q respectively.

What the output is giving you is the difference in memory locations. Usually you expect 60-40 to be 20, but in this case, you are getting 5 because in your machine each integer occupies 4 bytes or 32 bits.

So you can think of it like this: The first integer at 40 takes 4 places, so the next integer is at 44, then 48, then 52. Thus when getting the difference of memory locations, the program takes each 4 byte block as 1 block and there is a difference of 5 blocks between 40 and 60.

In Pointer math, this can be obtained like abs(mem_location1 - mem_location2)/sizeof(int) (ie no. of bytes occupied by an integer).

HTH. :)

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