4

I want to find out the (short / int / long / float / double / long double / char) size, so I wrote this code:

printf("short\t\t%d\n", sizeof(short));    
printf("int\t\t%d\n", sizeof(int));
printf("long\t\t%d\n", sizeof(long));
printf("float\t\t%d\n", sizeof(float));
printf("double\t\t%d\n", sizeof(double));  
printf("long double\t%d\n", sizeof(long double));    
printf("char\t\t%d\n", sizeof(char));   

BUT the output is:

type            bytes
short           512
int             512
long            1024
float           1024
double          1024
long double     1024
char            256

Why are the number of bytes so large?

Shouldn't it be 2, 8, ...?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
賴言厚
  • 45
  • 1
  • 1
  • 3

2 Answers2

7

sizeof evaluates to a size_t, not an int. So %d is not appropriate; you're invoking undefined behaviour.

To correctly print data of type size_t, I suggest e.g. printf("%zu\n", sizeof(float));, etc.

Michael Foukarakis
  • 39,737
  • 6
  • 87
  • 123
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • 1
    Or better, use `%zu` for `size_t`. In theory, undefined behavior could cause any problem, but I doubt that's the root problem as I can't reproduce the problem with `%d`. – Yu Hao Sep 20 '13 at 12:56
  • Related - [What's the difference between size_t and int in C++?](http://stackoverflow.com/questions/502856/whats-the-difference-between-size-t-and-int-in-c). – Bernhard Barker Sep 20 '13 at 12:56
-1

Use : format specifier long unsigned int. it will work fine. Ex: printf("sizeof(long double)= %lu\n", sizeof(long double));

Ans:16

akshaypmurgod
  • 77
  • 1
  • 3
  • 1
    This answer adds nothing to the accepted answer and is in fact wrong. There is no guarantee that `%lu` is a correct format specifier for `size_t`. – trent Oct 13 '17 at 19:48
  • Thanks for your feedback, can you correct me here ? I will remove my answer once you provide me the solution. – akshaypmurgod Oct 26 '17 at 06:20
  • `size_t` may be an alias for any unsigned type that has at least 16 bits. That is, it may be `unsigned short`, `unsigned int`, `unsigned long`, or `unsigned long long`. On "exotic" implementations it may even be `unsigned char`! When calling a function without a prototype, or a variadic function like `printf` that does not prototype its variadic arguments, you must guarantee that the *actual* type of the argument matches the type the function expects the argument to be; `%lu` is not the right format specifier unless `size_t` happens to be `unsigned long`. In C99 and later, `%zu` always works. – trent Oct 26 '17 at 14:26
  • [This question and its answers have more information.](https://stackoverflow.com/q/33648596) – trent Oct 26 '17 at 14:29