gpt4 book ai didi

c++ - 使用整数指针操作时如何确定整数数组的结尾?

转载 作者:可可西里 更新时间:2023-11-01 16:25:56 25 4
gpt4 key购买 nike

代码如下:

int myInt[] ={ 1, 2, 3, 4, 5 };
int *myIntPtr = &myInt[0];
while( *myIntPtr != NULL )
{
cout<<*myIntPtr<<endl;
myIntPtr++;
}

Output: 12345....<junks>..........

对于字符数组:(因为我们在末尾有一个 NULL 字符,所以在迭代时没有问题)

char myChar[] ={ 'A', 'B', 'C', 'D', 'E', '\0' };
char *myCharPtr = &myChar[0];
while( *myCharPtr != NULL )
{
cout<<*myCharPtr<<endl;
myCharPtr++;
}

Output: ABCDE

我的问题是因为我们说要添加 NULL 字符作为字符串的末尾,所以我们排除了此类问题!如果以防万一,规则是将 0 添加到整数数组的末尾,我们就可以避免这个问题。怎么说?

最佳答案

C 字符串约定是一个 char* 以一个 '\0' 字符结尾。对于数组或任何其他 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;
}

P.S Boost.Foreach 在 C++98 编译器上模拟基于范围的 for 循环

关于c++ - 使用整数指针操作时如何确定整数数组的结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2736062/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com