C - differentiate between 0 and \0 in integer array -
possible duplicate:
nul terminating int array
i'm trying print out elements in array:
int numbers[100] = {10, 9, 0, 3, 4}; printarray(numbers); using function:
void printarray(int array[]) { int i=0; while(array[i]!='\0') { printf("%d ", array[i]); i++; } printf("\n"); } the problem of course c doesn't differentiate between 0 element in array , end of array, after it's 0 (also notated \0).
i'm aware there's no difference grammatically between 0 , \0 looking way or hack achieve this:
10 9 0 3 4 instead of this
10 9 the array this: {0, 0, 0, 0} of course output still needs 0 0 0 0.
any ideas?
don't terminate array value in array.
you need find unique terminator.
since didn't indicate negative numbers in array, recommend terminating -1:
int numbers[100] = {10, 9, 0, 3, 4, -1}; if doesn't work, consider: int_max, or int_min.
as last resort, code sequence of values guaranteed not in array, such as: -1, -2, -3 indicates termination.
there nothing "special" terminating 0 or \0. terminate whatever works case.
if array can hold values in order, terminator isn't possible, , have keep track of length of array.
from example, like:
int numbers[100] = {10, 9, 0, 3, 4}; int count = 5; int i; for(i=0; i<count; ++i) { // numbers[i] }
Comments
Post a Comment