Nanthini Muniapan
Nanthini Muniapan

Reputation: 456

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

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

Answers (3)

EvilTeach
EvilTeach

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

another.anon.coward
another.anon.coward

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

Mac
Mac

Reputation: 14791

It assigns the character '\0' (i.e. the NUL character) to the 41st array element.

Upvotes: 1

Related Questions