賴言厚
賴言厚

Reputation: 45

Size of short, int, long, float, double long, double, char

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, ...?

Upvotes: 4

Views: 14493

Answers (2)

akshaypmurgod
akshaypmurgod

Reputation: 77

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

Ans:16

Upvotes: -1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272497

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.

Upvotes: 9

Related Questions