I'm trying to insert a null terminator at the end of this array. How would I fix it?
int cool_array[10] = {0};
int i = 0;
while (i < 5) {
cool_array[i] = 5;
i++;
}
cool_array[i] = {'\0'} // this is where the problem is. I get an error.
Error:
error: expected expression
legal_cards[legal_counter] = {'\0'};
^
1 error generated.
Firstly , null terminator at the end of this( integer ) array doesn't make any sense. if its char array
then it should be null terminated.
cool_array[i] = '\\0';
is not required as you already initialize cool_array
initially as below
int cool_array[10] = {0}; /* here itself cool_array all elements initialized with zero */
Secondly , if cool_array
is char array like char cool_array[10]
then it should be
cool_array[i] = '\0'; /* make sure i value is within range i.e 0 to 9 as you declare cool_array[10] */
Instead of
cool_array[i] = {'\0'};
As @achai pointed out, we usually reserve the term "null terminator" for use in connection with char
arrays containing string data. Nevertheless, there's nothing inherently wrong with using the value 0 as an end-of-data marker in arrays of other types, too, but such a convention is by no means universal.
You receive an error because the syntax of your terminator assignment is wrong. You are assigning to cool_array[i]
, which has type int
. The right-hand side of the assignment must therefore be an expression of type int
. That can be '\\0'
or (100% equivalent) just 0
, but the curly braces ( {}
) have no place there.
cool_array[i] = 0;
You are perhaps confused about the similar-appearing code in the declaration of cool_array
:
int cool_array[10] = {0};
Note well that that is a declaration, not an executable statement, and there is no assignment within. It contains an initializer for the array, but although that has similar form, both the syntax and semantics are different from an assignment. Specifically, it says to initialize the first element of the array (explicitly) to 0, and implicitly to initialize all other elements (to 0).
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.