printf("%lu \n", sizeof(*"327"));
I always thought that size of a pointer was 8 bytes on a 64 bit system but this call keeps returning 1. Can someone provide an explanation?
It returns the size of a variable. It can be applied to any data type, float type, pointer type variables. When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type.
The 'sizeof' operator returns size of a pointer, not of an array, when the array was passed by value to a function.
The sizeof(variable) operator computes the size of a variable. And, to print the result returned by sizeof , we use either %lu or %zu format specifier.
The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding. The result is the total number of bytes in the array. For example, in an array with 10 elements, the size is equal to 10 times the size of a single element.
Putting *
before a string literal will dereference the literal (as string literal are array of characters and will decay to pointer to its first element in this context). The statement
printf("%zu \n", sizeof(*"327"));
is equivalent to
printf("%zu \n", sizeof("327"[0]));
"327"[0]
will give the first element of the string literal "327"
, which is character '3'
. Type of "327"
, after decay, is of char *
and after dereferencing it will give a value of type char
and ultimately sizeof(char)
is 1
.
The statement:
printf("%lu \n", sizeof(*"327"));
actually prints the size of a char
, as using *
dereferences the first character of string 327
. Change it to:
char* str = "327"; printf("%zu \n", sizeof(str));
Note that we need to use %zu
here, instead of %lu
, because we are printing a size_t
value.
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