Trying to iterate through an array using pointers but I get float pointer error / it won't compile

Viewed 399

I am learning how pointers work in C++, and am trying to iterate through an array using pointers and that confusing pointer arithmetic stuff.

#include <iostream>

int main()
{
    float arr[5] = {1.0, 2.0, 3.5, 3.45, 7.95};
    float *ptr1 = arr;
    for (int i = 0; i < 5; *ptr1 + 1)
    {
        std::cout << *ptr1 << std::endl;
    }
}

I declare an array of type float called arr[5]. Then I initialize a pointer variable *ptr1 holding the memory address of arr. I try to iterate it using *ptr1+1 (which gives no error), but then when I do std::cout << *ptr1 + 1 << std::endl I get an error:

operator of * must be a pointer but is of type float

Please help me fix this.

2 Answers

In your loop, after each iteration, *ptr1 + 1 is dereferencing ptr1 to read the float it is currently pointing at, adding 1 to that value, and then discarding the result. You are not incrementing ptr1 itself by 1 to move to the next float in the array. You likely meant to use ptr1 += 1 instead of *ptr1 + 1.

More importantly, you are not incrementing i, so the loop will not terminate after 5 iterations. It will run forever.

The rest of the code is fine (though your terminology describing it needs some work).

Try this:

#include <iostream>
     
int main()
{
    float arr[5] = {1.0, 2.0, 3.5, 3.45, 7.95};
    float *ptr1 = arr;
    for (int i = 0; i < 5; ++i, ++ptr1)
    {
        std::cout << *ptr1 << std::endl;
    }
}

Online Demo

Though, a simpler way to write this would be to not use manual pointer arithmetic at all, just use normal array indexing notation instead:

#include <iostream>
     
int main()
{
    float arr[5] = {1.0, 2.0, 3.5, 3.45, 7.95};
    for (int i = 0; i < 5; ++i)
    {
        std::cout << arr[i] << std::endl;
    }
}

Online Demo

Or better, use a range-based for loop instead, and let the compiler do all the work for you:

#include <iostream>
     
int main()
{
    float arr[5] = {1.0, 2.0, 3.5, 3.45, 7.95};
    for (float f : arr)
    {
        std::cout << f << std::endl;
    }
}

Online Demo

You are actually adding 1 to the first float in the array but never increasing the pointer. And you don't increment the loop counter, therefore your program will run forever.

You need to correctly increase the pointer and also increase i:

#include <iostream>

int main()
{
    float arr[5] = {1.0, 2.0, 3.5, 3.45, 7.95};
    float *ptr1 = arr;
    for (int i = 0; i < 5; ++i, ++ptr1)
    {
        std::cout << *ptr1 << std::endl;
    }
}

Proof:

https://replit.com/@ichramm/PortlyMiserableNetframework#main.cpp

Related