简体   繁体   中英

Modifying Array Elements Using Pointers

I'm working on a program that modifies the data of an array using only pointers. I'm trying to return the index where array[ix]==0. However, I keep getting stuck in an infinite loop. What am I doing wrong?

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

You can use std::distance quite easily to get the index. More info on std::distance here

Btw, the function name is also very misleading. If the function is meant to return the index of a value in the array, then consider changing that function name, like getIndex() or find() . Just pick something more meaningful.

#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;
}

The result is:

0 found at index: 4

Online example: https://rextester.com/KVCL75042

To get the "distance" between two pointers (in the number of elements) you can either use std::distance :

return std::distance(arr, begin);  // Return the distance between current element and the beginning of the array

You can also subtract the pointers:

return begin - arr;  // Return the distance between the current element and the beginning of the array

The "distance" returned by the above two statements will be in the number of elements, and since you take the distance from the first element it will be the index of the "current" element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM