这是代码:
int myInt[] ={ 1, 2, 3, 4, 5 };
int *myIntPtr = &myInt[0];
while( *myIntPtr != NULL )
{
    cout<<*myIntPtr<<endl;
    myIntPtr++;
}
Output: 12345....<junks>..........
对于Character数组:(因为我们最后有一个NULL字符,迭代时没问题)
char myChar[] ={ 'A', 'B', 'C', 'D', 'E', '\0' };
char *myCharPtr = &myChar[0];
while( *myCharPtr != NULL )
{
    cout<<*myCharPtr<<endl;
    myCharPtr++;
}
Output: ABCDE
我的问题是,因为我们说要添加NULL字符作为字符串的结尾,我们排除了这样的问题!如果是这样的话,规则是在整数数组的末尾添加0,我们可以避免这个问题.说啥?
Vic*_*iba 12
C字符串约定是由'\ 0'char完成的char*.对于数组或任何其他C++容器,还有其他可以应用的习语.接下来是我的偏好
迭代序列的最佳方法是使用C++ 0x中包含的基于范围的for循环
int my_array[] = {1, 2, 3, 4, 5};
for(int& x : my_array)
{
  cout<<x<<endl;
}
如果您的编译器尚未提供此功能,请使用迭代器
for(int* it = std::begin(array); it!=std::end(array); ++it)
{
  cout<<*it<<endl;
}
如果你不能既不使用std :: begin/end
for(int* it = &array[0]; it!=&array[sizeof(array)]; ++it)
{
  cout<<*it<<endl;
}
PS Boost.Foreach在C++ 98编译器上模拟基于范围的for循环
小智 11
在C++中,最好的解决方案是使用std :: vector,而不是数组.矢量随身携带它们的大小.使用零(或任何其他值)作为结束标记的问题当然是它不能出现在数组的其他地方.对于字符串来说,这不是一个问题,因为我们很少想要使用代码零打印字符,但在使用整数数组时这是一个问题.
| 归档时间: | 
 | 
| 查看次数: | 36780 次 | 
| 最近记录: |