0
Arrays as function parameter - C++
I understand that the array passed as an argument is just a pointer to the first element of the array. Because you lose the size of the array - you also pass the size of the array as an argument. Now, when we iterate through the array in the function - you increment the memory address of the first element... till you reach the end of the array... My question is how can you access the value in the array by doing: arr[i]; If arr is a pointer to an element in the array, and you access through a pointer by using square brackets like it is a normal array.. how??
1 Resposta
+ 7
Consider a pointer
type *ptr;
Now, doing ptr[i] is the same as doing
*(ptr + i)
So for example, if there is a pointer
int *ptr;
Then,
ptr[0]
= *(ptr + 0)
= *ptr
ptr[1]
= *(ptr + 1)
Having known this, you can imaine what happens with an array as a pointer.
int arr[] = {1, 2, 3};
int *arrPtr = arr;
Now, doing arrPtr[0] is same as doing *arrPtr, which will give the first element 1. Similarly, arrPtr[1] is same as *(arrPtr+1), which give the element at index 1, which is 2.
In short, the way to access the ith index of an array is same irrespective of whether its type is array or pointer because the [] operator simply offsets the pointer by i in both cases.