Doubts cast in c

1

If I give a printf like this:

int x=5, *px = &x;
printf("%d %ld\n", x, (long)px);

Until then without Warning , but if you change the printf :

int x=5, *px = &x;
printf("%d %d\n", x, (int)px);

I get a warning:

  

warning: cast from pointer to integer of different size.

Why this warning? I've already been in some places and I've seen some very different '\ zu' operators and several others, does anyone know of an article that I can read about it? I get Warning all the time.

    
asked by anonymous 05.01.2018 / 21:04

2 answers

4

In 64-bit architectures, pointers occupy 8 bytes (that is, sizeof(int*) == 8 ). On the other hand, integers have 4 bytes (that is, sizeof(int) == 4 ). This can be easily proven:

#include <stdio.h>

int main(void) {
    printf("%ld %ld", sizeof(int*), sizeof(int));
}

This code outputs 8 4 .

See here working on ideone.

When you take a pointer and do a cast for integer, you'll be throwing out 4 bytes of its value. This is not problematic per se, but picking up a memory address and throwing away a part of it is not an operation that makes much sense in practice and probably will give you incorrect values and no practical service, so the compiler gives you a < in> warning .

    
05.01.2018 / 21:10
1

It is written in the notice itself. The type size is different.

Your int is probably 16-bit, and the long is 32-bit, and the pointer is 32-bit.

These sizes depend on the architecture.

Editing

It may be the case here, or not, of a little confusion, clarifying if this is the case: Declare

int *px = &x;

Creates a pointer that points to the address of the variable x, that is, px is a pointer. In the question you are converting a memory address to a int or long . To access the value stored in the address for which px points, you must use the "*", like this:

printf("%d %d\n", x, *px);

This will always print the same value twice. To print the value and then the address, use your very first example.

printf("%d %ld\n", x, (long)px);
    
05.01.2018 / 21:06