Possible Duplicate:
nul terminating a int array
I’m trying to print out all elements in an array:
int numbers[100] = {10, 9, 0, 3, 4};
printArray(numbers);
using this function:
void printArray(int array[]) {
int i=0;
while(array[i]!='\0') {
printf("%d ", array[i]);
i++;
}
printf("\n");
}
the problem is that of course C doesn’t differentiate between just another zero element in the array and the end of the array, after which it’s all 0 (also notated \0).
I’m aware that there’s no difference grammatically between 0 and \0 so I was looking for a way or hack to achieve this:
10 9 0 3 4
instead of this
10 9
The array could also look like this: {0, 0, 0, 0} so of course the output still needs to be 0 0 0 0.
Any ideas?
Don’t terminate an array with a value that could also be in the array.
You need to find a UNIQUE terminator.
Since you didn’t indicate any negative numbers in your array, I recommend terminating with
-1:If that doesn’t work, consider:
INT_MAX, orINT_MIN.As a last resort, code a sequence of values that are guaranteed not to be in your array, such as:
-1, -2, -3which indicates the termination.There is nothing “special” about terminating with
0or\0. Terminate with whatever works for your case.If your array truly can hold ALL values in ANY order, then a terminator isn’t possible, and you will have to keep track of the length of the array.
From your example, this would look like: