Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null-Terminated string

Tags:

c++

Which of the following are null-terminated string?

char *str1 = "This is a string.";
char *str2 = "This is a string.\0";
char str3[] = "This is a string.";
const char *str4 = "This is a string.";
const char *str5 = "This is a string.\0";
const char str6[] = "This is a string.";
like image 618
czx Avatar asked Dec 09 '10 07:12

czx


3 Answers

  • All : a string literal is a null terminated string
  • str2 and str5 have the particularity of being doubly null-terminated strings

Also :

  • char *str1 should be const char *str1
  • char *str2 should be const char *str2
like image 166
icecrime Avatar answered Sep 27 '22 22:09

icecrime


They are all null-terminated (str2 and str5 are actually doubly-null-terminated) because using double quotes is a shorthand for a null-terminated char array.

So this:

"Hello"

Is actually this:

{'H', 'e', 'l', 'l', 'o', '\0'}

Variables pointing to string literals such as these should be declared as const.

like image 38
Jacob Relkin Avatar answered Sep 27 '22 22:09

Jacob Relkin


All. C compiler auto aggregates string with a terminate '\0', then store it in a char[] or refer to it by char *;

like image 22
Huang F. Lei Avatar answered Sep 27 '22 21:09

Huang F. Lei