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.
ptr
is a pointer to the first element ofarr
.ptr[i]
is equivalent to*(ptr i)
, or in this casearr[i]
.- You see, there is an implicit dereferencing operation behind the scenes.
*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.