views:

443

answers:

1

I want to print out a variable for type size_t in c but it appears that size_t is aliased to different variable types on different architextures. For example on one machine (64-bit) the following code does not throw any warmings:

size_t size = 1;
printf("the size is %ld", size);

but on my other machine (32_bit) the above code produces the following warning message:

warning: format '%ld' expects type 'long int *', but argument 3 has type 'size_t *'

I suspect this is due to the fact that one machine is 64-bit and the other is 32-bit, so that on my 64-bit machine size_t is aliased to a long int (%ld), whereas on my 32-bit machine size_t is aliased to another type.

Is there a format specifier specifically for size_t?

+6  A: 

Yes: use the z length modifier:

size_t size = sizeof(char);
printf("the size is %zd\n", size);  // decimal size_t
printf("the size is %zx\n", size);  // hex size_t

The other length modifiers that are available are hh (for char), h (for short), l (for long), ll (for long long), j (for intmax_t), t (for ptrdiff_t), and L (for long double). See §7.19.6.1 (7) of the C99 standard.

Adam Rosenfield
whats the difference between zd and zu? I get that zd is decimal, but is it signed, if so how does zd being signed effect things.
e5
It's the difference between a `size_t` and an `ssize_t`; the latter is seldomly used.
Adam Rosenfield
Right, so in this case, you should be using `%zu`, because the argument is unsigned.
caf