C Programming Basics

char s[10] = "hello";
printf("%zu %zu\n", strlen(s), sizeof s);

Which of the following is the output when the code above, which concerns a char array holding a string, is executed?

  1. A5 10
  2. B6 10
  3. C10 10
Show answer and explanation

Answer: A. 5 10

A string in C is a sequence of characters followed by the terminating character '\0'. strlen counts the characters from the start up to just before '\0', so it gives 5 for "hello". sizeof s is the size of the whole array s, the declared 10 bytes (the remaining elements hold 0). Omitting the number of elements, as in char s[] = "hello"; gives a 6-byte array including '\0'.

  • A. Correct. strlen gives 5 without counting the terminating '\0', and sizeof gives the array's 10 bytes.
  • B. strlen does not count the terminating '\0', so it is 5, not 6.
  • C. strlen returns the number of characters before '\0', not the size of the array.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. After the declarations above, one of the statements A "p = t;", B "*p = 'x';", C "q = t;" or D "*q = 'x';" is written. Which of the following is the combination that causes compile errors?
  2. Which of the following is the output when the program above, which uses an array of function pointers, is executed?
  3. fill and use are functions defined elsewhere. Which of the following is a problem with the function above?
  4. Which of the following is true about the pointer returned by the function make above?
  5. In C, which of the following is the most appropriate reason it is recommended to write p = NULL; right after free(p);?