I just got into learning pointers in C++ and I have been trying some different instances of using them to get a better understanding to them but there is some I go into that seems a little weird to me.
The code below is for looping through an array and what I assumed after it ran well that arr
is just a pointer to the beginning of the array (because I could do ptr = arr;
.
int size = 3;
int arr[size] = {50, 30, 20};
int *ptr;
ptr = arr;
for (int i = 0; i < size; i++) {
std::cout << *ptr << std::endl;
ptr++;
}
But When I try looping through the same array but with using arr
instead of ptr
without assigning it to arr
it gave me an error (lvalue required as increment operand) referring arr++
.
This is the Code.
int size = 3;
int arr[size] = {50, 30, 20};
for (int i = 0; i < size; i++) {
std::cout << *arr << std::endl;
arr++;
}
I don't understand why the first one work and the second doesn't although they are both pointers(as far as I know).