如何在使用整数指针操作时确定整数数组的结尾? [英] How to determine the end of an integer array when manipulating with integer pointer?
问题描述
这里是代码:
int myInt[] ={ 1, 2, 3, 4, 5 };
int *myIntPtr = &myInt[0];
while( *myIntPtr != NULL )
{
cout<<*myIntPtr<<endl;
myIntPtr++;
}
Output: 12345....<junks>..........
对于字符数组:(因为我们在结尾处有一个NULL字符,迭代时没有问题)
For Character array: (Since we have a NULL character at the end, no problem while iterating)
char myChar[] ={ 'A', 'B', 'C', 'D', 'E', '\0' };
char *myCharPtr = &myChar[0];
while( *myCharPtr != NULL )
{
cout<<*myCharPtr<<endl;
myCharPtr++;
}
Output: ABCDE
说要添加NULL字符作为字符串的结尾,我们排除这样的问题!
如果在情况下,在整数数组的末尾添加0是规则,我们可以避免这个问题。什么说?
My question is since we say to add NULL character as end of the strings, we rule out such issues! If in case, it is rule to add 0 to the end of integer array, we could have avoided this problem. What say?
推荐答案
C字符串约定是一个char *由'\0'char完成。对于数组或任何其他C ++容器,还有其他可以应用的习语。接下来是我的首选项
C-strings convention is that a char* finish by a '\0' char. For array or any other C++ container there are other idioms that can be applied. Next follows my preferences
对序列进行迭代的最好方法是使用C ++ 0x上包含的基于范围的for-loop
The best way to iterate on sequences is to use the Range-based for-loop included on C++0x
int my_array[] = {1, 2, 3, 4, 5};
for(int& x : my_array)
{
cout<<x<<endl;
}
如果您的编译器没有提供,请使用iterators
If your compiler don't provide this yet, use iterators
for(int* it = std::begin(array); it!=std::end(array); ++it)
{
cout<<*it<<endl;
}
如果你不能同时使用std :: begin / end
And if you can not use neither std::begin/end
for(int* it = &array[0]; it!=&array[sizeof(array)]; ++it)
{
cout<<*it<<endl;
}
PS Boost.Foreach模拟基于范围的for循环C ++ 98个编译器
P.S Boost.Foreach emulates the Range-based for-loop on C++98 compilers
这篇关于如何在使用整数指针操作时确定整数数组的结尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!