why do I get results 6, and then 8 by from the following code? I searched through the posts but cannot find an exact match of my question. Thanks.
#include <stdio.h>
void getSize(const char *str)
{
printf("%d\n", sizeof(str)/sizeof(char));
}
int main()
{
char str[]="hello";
printf("%d\n", sizeof(str)/sizeof(char));
getSize(str);
}
sizeof() operator returns actual amount of memory allocated for the operand passed to it. Here the operand is an array of characters which contains 9 characters including Null character and size of 1 character is 1 byte. So, here the total size is 9 bytes.
As char 's size is always the minimum supported data type, no other data types (except bit-fields) can be smaller. The minimum size for char is 8 bits, the minimum size for short and int is 16 bits, for long it is 32 bits and long long must contain at least 64 bits.
In your getSize()
function, str
is a pointer. Therefore sizeof(str)
returns the size of a pointer. (which is 8 bytes in this case)
In your main()
function, str
is an array. Therefore sizeof(str)
returns the size of the array.
This is one of the subtle differences between arrays and pointers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With