Correct format specifier for return value of sizeof() in C

≯℡__Kan透↙ 提交于 2019-11-28 00:33:01

You're trying to print the return value of sizeof operator, which is usually of type size_t.

It appears, in your case, size_t is a typedef of long unsigned int, so it demands it's compatible format specifier %lu to be used. The returned value here does not matter, your problem is with the type mismatch.

Note: To have a portable code, it's safe to use %zu, on compilers based on C99 and forward standards.

In C the type of a sizeof expression is size_t.

The printf specifier to use is %zu. Example:

printf("The 'int' datatype is \t\t %zu bytes\n", sizeof(int));

It has been possible to use this since the 1999 version of the C standard.

Technically, you have undefined behaviour due to mismatched format and data types.

You should use %zu for the type associated with sizeof (which is size_t). For example:

 printf("The 'int' datatype is \t\t %zu bytes\n", sizeof(int));

This is particularly important if you intend to target both 32 and 64 bit platforms.

Reference: http://en.cppreference.com/w/c/io/fprintf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!