The following code has a problem, but compiles and runs fine
1 2 3 4 5 6 7 8 9 10 11 12 13 14
int &get(int *arry, int index)
{
return arry[index];
}
int main()
{
int ia[10];
for (int i = 0; i != 10; ++i) {
get(ia, i) = i;
cout << ia[i] << " ";
}
return 0;
}
PROB : We are passing ia, to *arry which would yield a pointer and not the array.
Maybe I`m wrong, what I learnt was that when we pass an array we are actually passing a pointer to the first element. Maybe I`m wrong so please tell me if I am
I learnt was that when we pass an array we are actually passing a pointer to the first element.
Yes. Therefore, you pass a pointer to the function.
The function stores that pointer in a pointer variable 'arry'. Then it uses that pointer in a normal way.
When you have a pointer, you can dereference it. One syntax is *arry, but that is equivalent to *(arry+0) and in turn equivalent to arry[0]. All three refer to value in the address that the pointer has.
'arry' is an 'int' pointer. If you take the address and add to it, say *(arry+7), you don't actually add '7' to the address, but the number of bytes that it takes to hold 7 int values.
1 2 3
int a[7];
int * b = &(a[2]);
// a[5] and b[3] refer to same element
Thank you both, yes that helped a lot. All this time I was confused about when a pointer points to the first element. Thought you could only access that element. Thank you