Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

pointers

#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?

like image 364
Bharat Kul Ratan Avatar asked Jul 20 '12 16:07

Bharat Kul Ratan


People also ask

What does int *) p mean in C?

int **p declares a pointer on the stack which points to pointer(s) on the heap. Each of that pointer(s) point to an integer or array of integers on the heap. This: int **p = new int*[100]; means that you declared a pointer on the stack and initialized it so that it points to an array of 100 pointers on heap.

What does int * P &A mean?

int *p=&a; is an initialization, not just a "declaration and assignment." There are differences between assignments and initializations; for example, objects with static duration may only be initialized with constants.

Is int * p and int * p same?

They are the same. The first one considers p as a int * type, and the second one considers *p as an int .

What does int *) do in C?

int* means a pointer to a variable whose datatype is integer. sizeof(int*) returns the number of bytes used to store a pointer. Since the sizeof operator returns the size of the datatype or the parameter we pass to it.


2 Answers

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.

like image 122
orlp Avatar answered Oct 05 '22 17:10

orlp


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 ints and so p - q equals 5 ((60 - 40) / 4).

like image 30
mattjgalloway Avatar answered Oct 05 '22 16:10

mattjgalloway