user707549
user707549

Reputation:

How many elements will be in the array?

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

How many elements will be in the array created by the declaration above?

Upvotes: 9

Views: 701

Answers (2)

Xeo
Xeo

Reputation: 131789

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. :)

Upvotes: 48

user142162
user142162

Reputation:

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 

Upvotes: 19

Related Questions