开发者

Why can I compile this in 32bit but not 64 bit?

开发者 https://www.devze.com 2023-02-10 19:57 出处:网络
user@user:~/langs/c$ cat 3264int.c #include <stdio.h> int main(){ long z; printf(\"Long int size is %d b开发者_开发知识库ytes long!\\n\", sizeof(z));
user@user:~/langs/c$ cat 3264int.c 
#include <stdio.h>
int main(){
        long z; 
    printf("Long int size is %d b开发者_开发知识库ytes long!\n", sizeof(z)); 

    return 0;
}
user@user:~/langs/c$ cat 3264int.c ^C
user@user:~/langs/c$ gcc -m32 -o 32int 3264int.c 
user@user:~/langs/c$ gcc -m64 -o 64int 3264int.c 
3264int.c: In function ‘main’:
3264int.c:4: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘long unsigned int’ cat 3264int.c

I tried changing the type for z to int, and it still fails to compile.


That's a warning, not an error. You got a resulting executable. However, if you're trying to compile with -pedantic or -Werror then you won't. If this microexample is what you're working with however, then what you need to do is change your format specifier to %ld. On your platform size_t which is what sizeof will return, is probably 8 bytes on 64-bit, but 4 bytes on 32-bit. %d can display a 32-bit integer, but not a 64-bit integer.


The sizeof operator returns size_t. On your platform in 32-bit builds this is equal in size to a 32-bit int (i.e., it most likely is an unsigned int or a long unsigned int, both of which are likely 32-bit for a 32-bit build). On 64-bit builds it is a long unsigned int, which is 64-bits. %d is for ints and ints are 32-bit on both 32-bit and 64-bit builds.

The way around this dilemma is to:

Cast the result of sizeof to a well defined platform independent type - unsigned int or better yet, unsigned long, and then use "%u" or "%lu", respectively, as the printf formatting character.

Or, you can:

Use the %zu formatting specification, which directly supports size_t.

0

精彩评论

暂无评论...
验证码 换一张
取 消