Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problems understanding the size_t type and the sizeof operator

void sizeof_test2();

void sizeof_test2()
{
    int array[5];
    size_t arr_size = sizeof(array);

    printf( "sizeof:\n"
            "array = %d\n"
            "arr_size = %d\n", sizeof(array), sizeof(arr_size));
}

GCC compiler output:

sizeof_test2.c: In function `sizeof_test2':  
sizeof_test2.c:6: error: `size_t' undeclared (first use in this function)  
sizeof_test2.c:6: error: (Each undeclared identifier is<br>
reported only once sizeof_test2.c:6: error: for each function it<br>
appears in.) sizeof_test2.c:6: error: parse error before "arr_size"<br>
sizeof_test2.c:10: error: `arr_size' undeclared (first use in this<br>
function) make[2]:  [build/Debug/Cygwin-Windows/sizeof_test2.o]<br>
Error 1 make[1]:  [.build-conf] Error 2<br>  

Don't know why I'm getting this error, what's the correct way of displaying a size_t type through printf?

like image 472
Petrus K. Avatar asked Dec 01 '25 02:12

Petrus K.


2 Answers

size_t type is defined in stddef.h header (and other headers, for example stdio.h).

Note that in your program your are using printf function so you already have to include stdio.h.

like image 155
ouah Avatar answered Dec 02 '25 15:12

ouah


stdlib is what you want, and for displaying it I think you're looking for the %z modifier

#include <stdlib.h>

size_t arr_size;
printf("%zu\n", arr_size);  // unsigned decimal 
printf("%zx\n", arr_size);  // hex 
like image 23
Mike Avatar answered Dec 02 '25 16:12

Mike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!