开发者

Null-Terminated string

开发者 https://www.devze.com 2023-01-29 09:29 出处:网络
Which of the following are null-terminated st开发者_C百科ring? char *str1 = \"This is a string.\";

Which of the following are null-terminated st开发者_C百科ring?

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.";


  • 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


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.


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


Don't use char*s="hi" in case you want to do something with the string like modifying it or even if you want to concatenate something to it because here stringhiis in read only section of the memory and your program can crash

0

精彩评论

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