0

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).

Moaz Cook
  • 3
  • 4
  • 1
    Arrays are not pointers. They are just converted to pointers. – MikeCAT Jan 13 '21 at 15:24
  • You're making an invalid assumption because of an implicit conversion - `ptr = arr;` is equivalent to `ptr = &arr[0];`. – molbdnilo Jan 13 '21 at 15:48
  • doesn't that mean that `arr` holds the address of `arr[0]` and what I know that this make `arr` a pointer (Pointers hold addresses). – Moaz Cook Jan 14 '21 at 19:42

0 Answers0