char array initialization

Microsoft Visual studio 2008 professiona...
April 4, 2010 at 13:01:21
Specs: Windows XP
I'm creating a lexer. I input letters one at a time from the file stream into a char array. Like 'function', but this word and others all have nonsensical characters at the end of the array even if I initialize it as: char array[] = "\0"; how can i initialize it as an empty array and reinitialize it to empty the second time through?

See More: char array initialization

Report •

April 4, 2010 at 15:12:47
Looking at your statement:

char array[] = "\0";

What does it actually do? An auxilliary question, how big an
array does it declare? char array[] means you are not
specifying the size, but it takes the size from the initializer: =

So what exactly is the type and size of "\0"? Answer: it is a
two-element array, containing two NUL characters. Why?
First, the empty string "" is a one-element array containing
the NUL terminator. Any string literal, say "a", ends with a
NUL terminator. So "\0" both contains a NUL character and is
followed by another NUL character.

So you have declared a two-element array. Is that what you
want? When you input a word like "function", how do you
protect against overwriting memory past the array elements
that you have allocated?

Next, when you say you "reinitialize it as empty the second
time through" what exactly do you mean by empty? A char
array is a fixed size. It has the size that you allocated for it at
the start. By convention, a NUL character is often treated as a
string terminator, so you can think of an array starting with
the NUL character as an empty string. To do that, you need
to do this:

array[0] = '\0';

Also, notice the crucial difference between '\0' and "\0".

Report •

April 4, 2010 at 19:19:54
I switched from char arrays to strings and instead of inputting one char at a time into an array i append the incoming char to the last one. This allows me to use the clear() function in between loops. Thanks for the help, though.

Report •

Related Solutions

Ask Question