Home > OS >  Why value at operator(*) not work when the pointer is pointing to an array?
Why value at operator(*) not work when the pointer is pointing to an array?

Time:12-26

I have the following two code snippets to copy an array into another array in C written VS Code :

Snippet 1 ~

int arr[5]={1,2,3,4,5};
int arr_copy[5];
int *ptr = arr;
for(int i=0; i<5;i  )
{
    arr_copy[i]=*ptr[i];
}

Snippet 2~

    int arr[5]={1,2,3,4,5};
    int arr_copy[5];
    int *ptr=arr;
    for(int i=0; i<5;i  )
    {
        arr_copy[i]=ptr[i];
    }

The first snippet throws an error on compilation saying *ptr[i] is invalid but the second snippet works. Shouldn't the first one return the value stored at pointer ptr[i] whereas second one should return the integer address of ptr[i]? Is it just the way C syntax is written or is there some logic behind it?

CodePudding user response:

Let’s go through this step by step.

  1. ptr is a pointer to the first element of arr.
  2. ptr[i] is equivalent to *(ptr i), or in this case arr[i].
    • You see, there is an implicit dereferencing operation behind the scenes.
  3. *ptr[i] would attempt to reference the integer value stored in the array, that is, to read memory from a somewhat arbitrary position. This will fail almost always.
  • Related