开发者

C - differentiate between 0 and \0 in integer array [duplicate]

This question already has answers here: Closed 12 years ago.

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 cou开发者_开发百科ld 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:

int numbers[100] = {10, 9, 0, 3, 4, -1};

If that doesn't work, consider: INT_MAX, or INT_MIN.

As a last resort, code a sequence of values that are guaranteed not to be in your array, such as: -1, -2, -3 which indicates the termination.

There is nothing "special" about terminating with 0 or \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:

int numbers[100] = {10, 9, 0, 3, 4};
int Count = 5;
int i;

for(i=0; i<Count; ++i)
{
    // do something with numbers[i]
}


The typical ways to implement this are to:

  • define a sentinel value (which others have suggested)
  • define a struct with an int (the actual value) and a bool (indicating if it's the sentinel) and make an array of those instead
  • pass the length of the array with the array
  • define a struct that contains both the array and the length and pass that instead

Note that the first and second items are nearly identical.


For an array declared as

int numbers[100] = {10, 9, 0, 3, 4};

there's absolutely no way to distinguish the explicit 0 in the initializer from the implicit zeros used to initialize the tail portion of the array. They are the same zeros. So, what you want to do cannot be done literally.

The only way you can do it is to select some int value as a reserved dedicated terminator value and always add it at the end of the array explicitly. I.e. if you choose -42 as a terminator value, you'd have to declare it as

int numbers[100] = {10, 9, 0, 3, 4, -42};

and iterate up to the first -42 in your cycles.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜