简体   繁体   中英

What happens when a char array is initialized to '\0'?

I have a char array of size 512 ie

char buffer [512];

This variable after some point is modified to this

buffer [40] = '\0';

What does this assignment does to the variable? Does it initialize the first 40 char in the array to null?

No. It stores the value NUL at the 41st position in the array.

To init the first 40 characters to NUL

memset(buffer, '\0', 40);

To init the entire buffer to NUL at compile time, try

char buffer[512] = {0}; 

or

char buffer[512] = "";

To init it at run time, try

memset(buffer, '\0', sizeof (buffer));

It assigns only the 41st char in the array to \\0 . Thus now the string consists of what the chars represent in the first 40 elements of the array ie 0 to 39th indices (assuming there were no other NUL characters in any of the previous elements -Thanks Kerrek SB!!) .
Hope this helps!

它将字符'\\0' (即NUL字符)分配给第41个数组元素。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM