我有一个类型的变量size_t,我想用它打印printf().我使用什么格式说明符来便携地打印它?
在32位机器上,%u似乎是对的.我编译了g++ -g -W -Wall -Werror -ansi -pedantic,并没有警告.但是当我在64位机器中编译该代码时,它会产生警告.
size_t x = <something>;
printf( "size = %u\n", x );
warning: format '%u' expects type 'unsigned int',
but argument 2 has type 'long unsigned int'
Run Code Online (Sandbox Code Playgroud)
正如预期的那样,警告会消失,如果我将其更改为%lu.
问题是,如何编写代码,以便在32位和64位机器上编译警告?
编辑:作为一种解决方法,我想一个答案可能是将变量"转换"为一个足够大的整数,比如说unsigned long,并使用打印%lu.这在两种情况下都有效.我在寻找是否还有其他想法.
前言: 我对结构对齐的研究.看着这个问题,这一个也是这个 - 但仍然没有找到我的答案.
我的实际问题:
这是我创建的代码片段,以澄清我的问题:
#include "stdafx.h"
#include <stdio.h>
struct IntAndCharStruct
{
int a;
char b;
};
struct IntAndDoubleStruct
{
int a;
double d;
};
struct IntFloatAndDoubleStruct
{
int a;
float c;
double d;
};
int main()
{
printf("Int: %d\n", sizeof(int));
printf("Float: %d\n", sizeof(float));
printf("Char: %d\n", sizeof(char));
printf("Double: %d\n", sizeof(double));
printf("IntAndCharStruct: %d\n", sizeof(IntAndCharStruct));
printf("IntAndDoubleStruct: %d\n", sizeof(IntAndDoubleStruct));
printf("IntFloatAndDoubleStruct: %d\n", sizeof(IntFloatAndDoubleStruct));
getchar();
}
Run Code Online (Sandbox Code Playgroud)
它的输出是:
Int: 4
Float: 4
Char: 1
Double: 8
IntAndCharStruct: 8
IntAndDoubleStruct: 16 …Run Code Online (Sandbox Code Playgroud)