'0'
is the "ASCII character0
" and has the value0x30
.'\0'
is the character representing the value0
and has the value0
.0
is just the value0
.pt
is an array of4
integers, so its size is 4x the size of an integer on our machine (which is evidently 4), so you get16
.- Since
pt
is an array of integers whose first value is0
, which is0x30
, that value as an integer is0x00000030
. When you type castpt
to a character pointer, then it looks like a pointer to a character string whose first 3 values are zero. So thestrlen
is0
(EDIT: because of the endianness of your particular architecture).
What's the difference among '0', '\0' and 0 with sizeof() and strlen()?
سؤال
#include <iostream>
int main(int argc, char* argv[])
{
int pt[4] = {'0','\0',0};
std::cout<<"size of pt: "<<sizeof(pt)<<std::endl;
std::cout<<"strlen of pt: "<<strlen((char*)pt)<<std::endl;
}
the result is:
size of pt: 16
strlen of pt: 1
and when I change int pt[4] = {'0','\0',0};
to int pt[4] = {'\0','0',0};
the result is
size of pt: 16
strlen of pt: 0
Why?
المحلول
نصائح أخرى
'0'
is a character with the value 48, representing the printable and displayable digit.
'\0'
and 0
are both the value 0, with the first having a character type and the second being an integer literal.
sizeof
gives the number of bytes in an object or array. strlen
counts the number of bytes from the start of an array of char
to the first byte with the value 0, and does not include the terminating 0. In the case of your example, you have an array of 4 ints, with each int taking 4 bytes; 4*4=16.
لا تنتمي إلى StackOverflow