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.
i;ptr1's location and NOT the actual indexfloatcalledarr[5]" - you are declaring an array of typefloat[5]namedarr. "I initialize a pointer variable*ptr1holding the memory address ofarr" - you are declaring a pointer of typefloat*namedptr1, and initializing it with the address of the 1st element ofarr, due to array-to-pointer decay. "I try to iterate it using*ptr1+1" - that doesn't iterate anything. "when I dostd::cout << *ptr1 + 1 << std::endlI get an error" - that statement does not produce that error.