Reputation: 456
I have a char array of size 512 i.e
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?
Upvotes: 2
Views: 240
Reputation: 28837
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));
Upvotes: 5
Reputation: 11395
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 i.e 0 to 39th indices (assuming there were no other NUL
characters in any of the previous elements -Thanks Kerrek SB!!) .
Hope this helps!
Upvotes: 3
Reputation: 14791
It assigns the character '\0'
(i.e. the NUL
character) to the 41st array element.
Upvotes: 1