why sizeof("")
is equivalent to 1 and sizeof(NULL)
is equivalent to 4 in c-language ?
Because in C character constants, such as 'a' have the type int . There's a C FAQ about this suject: Perhaps surprisingly, character constants in C are of type int, so sizeof('a') is sizeof(int) (though this is another area where C++ differs). Save this answer.
sizeof(NULL) is 8 in C in a 64 bit system. The difference is because NULL in C is a variable of a void pointer type with a value zero. In C++,NULL is a variable with a value zero that gets deduced to an int type.
The string is terminated by a null character. Array elements after the null character are not part of the string, and their contents are irrelevant. The length of a null string is 0.
Since NULL is defined as ((void*)0), we can think of NULL as a special pointer and its size would be equal to any pointer. If the pointer size on a platform is 4 bytes, the output of the above program would be 4. But if the pointer size on a platform is 8 bytes, the output of the above program would be 8.
NULL in C is defined as (void*)0. Since it's a pointer, it takes 4 bytes to store it. And, "" is 1 byte because that "empty" string has EOL character ('\0').
The empty string ""
has type char[1]
, or "array 1 of char
". It is not a pointer, as most people believe. It can decay into a pointer, so any time a pointer to char
is expected, you can use an array of char
instead, and the array will decay into a pointer to its first element.
Since sizeof(char)
is 1 (by definition), we therefore have sizeof("")
is sizeof(char[1])
, which is 1*1 = 1.
In C, NULL
is an "implementation-defined null pointer constant" (C99 §7.17.3). A "null pointer constant" is defined to be an integer expression with the value 0, or such an expression cast to type void *
(C99 §6.3.2.3.3). So the actual value of sizeof(NULL)
is implementation-defined: you might get sizeof(int)
, or you might get sizeof(void*)
. On 64-bit systems, you often have sizeof(int) == 4
and sizeof(void*) == 8
, which means you can't depend on what sizeof(NULL)
is.
Also note that most C implementations define NULL
as ((void*)0)
(though this is not required by the standard), whereas most C++ implementations just define NULL
as a plain 0
. This means that the value of sizeof(NULL)
can and will change depending on if code is compiled as C or as C++ (for example, code in header files shared between C and C++ source files). So do not depend on sizeof(NULL)
.
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