Re: sizeof()'s strange behviour



Keith Thompson wrote:
Richard Heathfield <rjh@xxxxxxxxxxxxxxx> writes:
arnuld said:
[...]
printf("sizeof(%s): %d\n", s, sizeof(s));
...so we'd expect this to print 16 in place of the second % format
specifier. Note that your printf is misleading. It will print:

sizeof(Saurabh Nirkhey): 16

but in fact it's sizeof s that is 16.
[...]

Furthermore, "%d" causes printf to expect an int argument, but
sizeof(s) is of type size_t. It's likely to happen to work on systems
where int and size_t are the same size, but the right way is (with a
couple of other tweaks):

printf("sizeof s: %d\n", (int)sizeof s);

Richard mentioned this already in his post.

I'd add that C99 provides the 'z' format modifier for size_t values:

printf("sizeof s: %zd\n", sizeof s);

....although if your code isn't C99 for other reasons, this is hardly a
great reason to break C90 compatibility.
.



Relevant Pages

  • Re: offset of a bit field
    ... but you're passing a size_t where printf expects an ... int. ... Use the %zu specifier if using C99, or %lu and an unsigned long cast ...
    (comp.lang.c)
  • Re: Can somebody help...
    ... a number of unsafe constructs and non-standard extensions. ... That value is too large to portably store in an int. ... This results in undefined behavior because you lied to printf about what ...
    (comp.lang.cpp)
  • Re: Is this correct..??
    ... long int i; ... Almost everthing is defined in assembler. ... Easily defeated by compiler optimisations. ... printf and that the first assignment to i is never used and decides to ...
    (comp.lang.c)
  • Semaphores Block when they Shouldnt and Dont when they Should
    ... took the votes (encoded in the first character of the transmitted mes- ... int socketAccess; ... write(voteSocket, voteBuffer, 2); ... {printf("Couldn't make a socket.\n"); ...
    (comp.unix.programmer)
  • RSA encrypt/decrypt c program
    ... Encrypt or Decrypt? ... int i,number; ... printf;} ... scanf; ...
    (comp.programming)