Doubts cast in c

Asked

Viewed 91 times

1

If I give a printf thus:

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

So far without Warning none, but if I 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.

What’s with the warning? I’ve been in some places and seen some very different operations ' zu' and several others, does anyone know an article that I can read just about this topic? I get Warning all the time.

2 answers

4


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

#include <stdio.h>

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

This code produces as output 8 4.

See here working on ideone.

When you grab a pointer and make a cast for whole, you will be throwing away 4 bytes of your value. This is not problematic in itself, but taking a memory address and throwing away a part of it is not an operation that makes a lot of sense in practice and will probably provide you with incorrect values and no practical use, so the compiler gives you a Warning.

  • I compiled this code of yours and received this warning: Warning: format '%d' expects argument of type ' int', but argument 2 has type 'long unsigned int but the result and esseq same, 8 and 4

  • @Fernando I switched to use %ld. This solves your Warning?

  • Solved, could explain me the pq ?

  • @Fernando Esse l is the prefix for long, as explained in the table of that page.

  • Obg for help, I’ll take a look at the table

1

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

Probably its int is 16 bits and the long is 32 bits, and the pointer is 32 bits.

These sizes depend on architecture.

Editing

This may or may not be the case here for a little confusion, clarifying whether this is the case: Declare

int *px = &x;

Creates a pointer that points to the address of the variable x, i.e., px is a pointer. In question you are converting a memory address to a int or long. To access the value stored at the address to which px points, needs to use "*", 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 first example.

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.