سؤال

#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 the "ASCII character 0" and has the value 0x30.
  • '\0' is the character representing the value 0 and has the value 0.
  • 0 is just the value 0.
  • pt is an array of 4 integers, so its size is 4x the size of an integer on our machine (which is evidently 4), so you get 16.
  • Since pt is an array of integers whose first value is 0, which is 0x30, that value as an integer is 0x00000030. When you type cast pt to a character pointer, then it looks like a pointer to a character string whose first 3 values are zero. So the strlen is 0 (EDIT: because of the endianness of your particular architecture).

نصائح أخرى

'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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top