C - 在整数数组中区分0和\ 0

Gal*_*Gal 1 c printing arrays zero

可能重复:
nul终止一个int数组

我正在尝试打印出数组中的所有元素:

int numbers[100] = {10, 9, 0, 3, 4};
printArray(numbers); 
Run Code Online (Sandbox Code Playgroud)

使用此功能:

void printArray(int array[]) {
    int i=0;
    while(array[i]!='\0') {
        printf("%d ", array[i]);
        i++;
    }
    printf("\n");
}
Run Code Online (Sandbox Code Playgroud)

问题是当然C不能区分数组中的另一个零元素和数组的结尾,之后它全部为0(也标注为\ 0).

我知道0和\ 0之间在语法上没有区别所以我正在寻找一种方法或黑客来实现这一点:

10 9 0 3 4
Run Code Online (Sandbox Code Playgroud)

而不是这个

10 9
Run Code Online (Sandbox Code Playgroud)

该数组也可能如下所示:{0,0,0,0}因此当然输出仍然需要为0 0 0 0.

有任何想法吗?

abe*_*nky 9

不要终止具有也可能在数组中的值的数组.

你需要找到一个UNIQUE终结器.

由于您没有在数组中指出任何负数,我建议终止-1:

int numbers[100] = {10, 9, 0, 3, 4, -1};
Run Code Online (Sandbox Code Playgroud)

如果这不起作用,请考虑:INT_MAX,或INT_MIN.

作为最后的手段,编写一系列保证不在您的数组中的值,例如:-1, -2, -3表示终止的值.

关于终止0或没有任何"特殊" \0.终止任何适合您案件的工作.


如果你的数组真的可以按任意顺序保存所有值,那么终结器是不可能的,你必须跟踪数组的长度.

从您的示例中,这将看起来像:

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

for(i=0; i<Count; ++i)
{
    // do something with numbers[i]
}
Run Code Online (Sandbox Code Playgroud)