Sizeof(char[]) in C

后端 未结 8 1900
情深已故
情深已故 2021-01-17 18:15

Consider this code:

 char name[]=\"123\";
 char name1[]=\"1234\";

And this result

The size of name (char[]):4
The size of n         


        
8条回答
  •  一个人的身影
    2021-01-17 18:40

    A String in C (and in, probably, every programming language - behind the scenes) is an array of characters which is terminated by \0 with the ASCII value of 0.

    When assigning: char arr[] = "1234";, you assign a string literal, which is, by default, null-terminated (\0 is also called null) as you can see here.

    To avoid a null (assuming you want just an array of chars and not a string), you can declare it the following way char arr[] = {'1', '2', '3', '4'}; and the program will behave as you wish (sizeof(arr) would be 4).

提交回复
热议问题