What is the last entry in an unfilled array (C++)?
I put C++ because I'm just starting in C# and I'm not sure if there's a difference.
if you declare an array
char arr[10]
and fill in values for arr[0] through arr[8], what value will be put in arr[9]?
a space ' '? An endline '\n'? '\0'? Or is it nothing at all?
I'm asking this because I've always used tactics like this
char word[20];
for(count = 0 ; count < 20 ; count++)
{
cout << word[count];
}
to print the entire contents of an array, and I was wondering if I could simplify it (e.g., if the last entry was '\0') by using something like this
char word[20];
while(word[count] != '\0')
{
cout &开发者_如何学运维lt;< word[count];
}
that way, I wouldn't have to remember how many pieces of data were entered into an array if all the spaces weren't filled up.
If you know an even faster way, let me know. I tend to make a bunch of mistakes on arrays.
The C# syntax for constructing a character array is:
char[] arr = new char[10];
All values in the array will be initialized to '\0'
.
Perhaps a List<char>
would be better for your situation where you don't know how many characters you need. Another option to consider is a StringBuilder
. Or use a string
if you don't need mutability.
In C++ an array declared like char word[20]
will essentially have garbage at every entry. It does not have nice default values like C# but instead likely just has whatever previously occupied that particular place in memory. In short don't trust the value unless you've explicitly set it yourself.
精彩评论