开发者

How many elements will be in the array?

char a [] = "EFG\r\n" ;

How many elements will开发者_如何学C be in the array created by the declaration above?


6, with proof by Ideone (look at the errors).


Edit: Actually, the example looked like this at first:

#include <iostream>

template<class T, int N>
int length_of(T (&arr)[N]){
  return N;
}

int main(){
  char a [] = "EFG\r\n" ;
  std::cout << length_of(a) << std::endl;
}

But I wanted to keep it short and avoid includes. :)


6 characters: E F G \r \n \0

You can see this for yourself by running:

char a [] = "EFG\r\n" ;
printf("%d\n", sizeof(a));
// 6

The following code shows you the value for each byte:

char a [] = "EFG\r\n" ;
int length = sizeof(a), i;
for(i = 0; i < length; i++)
{
    printf("0x%02x ", a[i]);
}
// 0x45 0x46 0x47 0x0d 0x0a 0x00 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜