Pointer And Array

When declaring an array:

int my_array[] = {1,23,17,4,-5,100}; 

The my_array will point to the first element of the int my_array[].

So:

#include <stdio.h>


int main()
{
    int my_array[] = {1,23,17,4,-5,100};
    printf("Pointer of my_array is %p, value is %d\n", my_array, *my_array);
    printf("Pointer of &my_array[0] is %p, value is %d\n", &(my_array[0]), my_array[0]);
}
Pointer of my_array is 0x16d27ad90, value is 1
Pointer of &my_array[0] is 0x16d27ad90, value is 1

Therefore, my_array == &my_array[0] or we say my_array will refer to the address of the first element in the array.

[!note]
In array, int my_array[] = {1,23,17,4,-5,100}, my_array refers to the first element of the array. But also &my_array will refer to the address of the same element as well.

So in other word, my_array == &my_array == &my_array[0]

Note: this is only true for array. If we do int *ptr = my_array and &ptr it will be a different value

Howerver, my_array is constant

It's important to note that my_array is a unmodifiable lvalue and cannot be changed.

So therefore, you cannot do my_array++. So how do we solve this problem?

We have to convert my_array to an rvalue.

int main() {
    int my_array[] = {1,23,17,4,-5,100};
    int *ptr = my_array;

    for (int i = 0; i < 6; i++) {
        printf("%d\n", *(ptr++));
    }
}

Now, since my_array is in the right side, it becomes rvalue, the compiler will simply go to my_array and copy the value it's storing (the memory address of the first element in the array).

As a result, we can then now iterate through the array:

1
23
17
4
-5
100