Why the disparity with sizeof result?
I see the sizeof operator in a lot of examples, and the concept seems simple enough and I use it sometimes. I might use it more if I understood this:
Code:
const int BUF = 40; |
sizeof is a compile-time operator; if you pass it a pointer, it will dutifully tell you the size of a pointer. That is 8 bytes if compiling a 64 bit program, 4 bytes for a 32 bit one. If you want to check on the string being pointed-to, strlen is the correct function to use.
|
Note: sizeof is evaluated compile-time, except for VLAs (variable length arrays). (Explanation: https://tvtropes.org/pmwiki/pmwiki.p...inkThisThrough ).
|
Quote:
|
I believe the C standard say that sizeof (char) is always 1, so this particular use of sizeof isn't that useful.
char *my_pointer = calloc(40, sizeof *my_pointer); is probably better as it will still work if you change the type to something other than char. i.e. you get enough storage allocated for 40 of whatever type *my_pointer is declared as. (comes into its own when used for arrays of structs) |
Thanks for the additional tips :)
|
All times are GMT -5. The time now is 08:20 AM. |