LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Why the disparity with sizeof result? (https://www.linuxquestions.org/questions/programming-9/why-the-disparity-with-sizeof-result-4175658309/)

Andy Alt 07-30-2019 08:14 PM

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;
  char *string1 = calloc (BUF, sizeof (char));
  /* calloc error checking */
  char string2[BUF];

size of string1 is 8, and the sizeof string2 is 40. Even after I copy a 10 character string into string1, sizeof still reports 8. So basically I resort to strlen() most of the time for error checking.

ntubski 07-30-2019 08:33 PM

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.

NevemTeve 07-30-2019 10:45 PM

Note: sizeof is evaluated compile-time, except for VLAs (variable length arrays). (Explanation: https://tvtropes.org/pmwiki/pmwiki.p...inkThisThrough ).

Andy Alt 07-31-2019 12:17 AM

Quote:

Originally Posted by NevemTeve (Post 6020025)
Note: sizeof is evaluated compile-time, except for VLAs (variable length arrays). (Explanation: https://tvtropes.org/pmwiki/pmwiki.p...inkThisThrough ).

I think that link might need to be changed... but I found some info about VLAs, thanks. :)

GazL 07-31-2019 08:21 AM

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)

Andy Alt 07-31-2019 02:08 PM

Thanks for the additional tips :)


All times are GMT -5. The time now is 08:20 AM.