C - 区分整数数组中的 0 和 \0
可能的重复:
nul 终止 int 数组
我正在尝试打印数组中的所有元素:
int numbers[100] = {10, 9, 0, 3, 4};
printArray(numbers);
使用这个函数:
void printArray(int array[]) {
int i=0;
while(array[i]!='\0') {
printf("%d ", array[i]);
i++;
}
printf("\n");
}
问题是,C 当然不会区分数组中的另一个零元素和数组末尾,之后都是 0(也表示为 \0)。
我知道 0 和 \0 在语法上没有区别,所以我正在寻找一种方法或黑客来实现这一点:
10 9 0 3 4
而不是
10 9
这个数组也可以看起来像这样:{0, 0, 0, 0} 所以当然输出仍然需要是 0 0 0 0。
有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不要使用也可能存在于数组中的值来终止数组。
您需要找到一个唯一终止符。
由于您没有在数组中指示任何负数,因此我建议以
-1
终止:如果这不起作用,请考虑:
INT_MAX
或INT_MIN
。作为最后的手段,编写一个保证不在数组中的值序列,例如:
-1, -2, -3
表示终止。以
0
或\0
终止并没有什么“特别”之处。以适合您的情况的方式终止。如果您的数组确实可以按任意顺序保存所有值,则不可能使用终止符,并且您将必须跟踪数组的长度。
从你的例子来看,这看起来像:
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, -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:
实现这一点的典型方法是:
请注意,第一项和第二项几乎相同。
The typical ways to implement this are to:
Note that the first and second items are nearly identical.
对于声明为 的数组,
绝对没有办法区分初始化器中的显式
0
和用于初始化数组尾部部分的隐式零。它们是相同的零。所以,你想做的事情不能从字面意义上去做。唯一的方法是选择一些
int
值作为保留的专用终止符值,并始终将其显式添加到数组的末尾。即,如果您选择-42
作为终止符值,则必须将其声明为并迭代到循环中的第一个
-42
。For an array declared as
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 asand iterate up to the first
-42
in your cycles.