KRISHNA I
KRISHNA I

Reputation: 67

cast of int,unsigned int for pointers in c

I am new to pointers in C. Please help me with following code:

void main()
{
    int i=3;
    printf("unsighed Address of i = %u \n",(unsigned int)&i);
    printf("int Address of i = %d\n",(int)&i);
    printf("pointer Address of i = %p\n",&i);
    printf("Value of i = %d\n",i);
}

Output:

unsighed Address of i = 3219915640 
int Address of i = -1075051656
pointer Address of i = 0xbfec0378
Value of i = 3

As you can see, I am just checking address of i through int, unsigned int, and pointer. Unsigned and pointer values are same (0xbfec0378 of base16 = 3219915640 of base10). But integer value is different. int range is (-32768 to 32767). So I don't know how I got -1075051656. Can you explain this.

Upvotes: 0

Views: 3495

Answers (2)

Jorge Bellon
Jorge Bellon

Reputation: 3106

If you want to cast a pointer value to an integer type, you should use intptr_t or uintptr_t, which warrantee that the integer is big enough to hold any possible pointer value.

You may be compiling your code for a 32bit architecture, or you may be lucky enough so that your stack is located in the lower area of the address space (although this is unlikely), so that in your execution the most significant bits of the address are 0.

See https://en.cppreference.com/w/c/types/integer

Code (https://ideone.com/2NDYnP):

#include <stdio.h>    // printf
#include <stdint.h>   // intptr_t, uintptr_t
#include <inttypes.h> // PRIdPTR, PRIuPTR

int main() {
    int i=3;
    // Incorrect
    printf("unsighed value of &i = %u \n",(unsigned int)&i);
    printf("int value of &i = %d\n",(int)&i);

    // Correct
    printf("pointer Address of i = %p\n",&i);
    printf("uintptr_t value of &i = %"PRIuPTR"\n", (uintptr_t)&i);
    printf("intptr_t value of &i = %"PRIdPTR"\n", (intptr_t)&i);

    printf("Value of i = %d\n",i);

    return 0;
}

Result:

unsighed value of &i = 3131233804 
int value of &i = -1163733492
pointer Address of i = 0x7fffbaa2d60c
uintptr_t value of &i = 140736324621836
intptr_t value of &i = 140736324621836
Value of i = 3

Upvotes: 1

kkica
kkica

Reputation: 4104

Where do you base int range is (-32768 to 32767)? That implies that the size is 2 bytes. I don't think that is the case, since -1075051656 is an int (you converted the address to int).

To check the size of an int use sizeof(int), or to find the interval of values it represents, use INT_MIN, INT_MAX constants.

The size of int in your system is probably 4 bytes (32 bits), with interval -2147483648 to 2147483647. With unsigned int it is from 0 to 4,294,967,295.

Therefore you can print the value using unsigned int, but it overflows when converting to int since 4294967295 > 3219915640 > 2147483647

Upvotes: 1

Related Questions