gpt4 book ai didi

c++ - 使用指针修改数组元素

转载 作者:搜寻专家 更新时间:2023-10-31 01:26:02 26 4
gpt4 key购买 nike

我正在开发一个仅使用指针修改数组数据的程序。我正在尝试返回 array[ix]==0 的索引。但是,我一直陷入无限循环。我做错了什么?

int firstprime(int size, int arr[]){
int* end = arr + size;
int* begin = arr;
while(begin<end){
if(*begin==0)
return *begin;
begin++;
}
return -1;
}

最佳答案

您可以很容易地使用 std::distance 来获取索引。有关 std::distance 的更多信息 here

顺便说一句,函数名也很容易误导人。如果该函数旨在返回数组中某个值的索引,请考虑更改该函数名称,例如 getIndex()find()。只需选择更有意义的内容即可。

#include <iostream>

int firstprime(int size, int *arr)
{
int *begin = arr;
int *end = begin + size;
while( begin < end )
{
if(*begin==0)
return std::distance(arr, begin);
begin++;
}
return -1;
}

int main()
{
int array[10] = {1,2,3,4,0,6,7,8,9,10};
int p = firstprime(10, array);
std::cout<< "0 found at index: " << p <<std::endl;
}

结果是:

0 found at index: 4

在线示例:https://rextester.com/KVCL75042

关于c++ - 使用指针修改数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55918400/

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