I'm reading Kochan's book "Programming in C". In section Pointer and Arrays on p. 264 he says:
In general, the process of indexing an array takes more time to execute than does the process of accessing the contents of a pointer. In fact, this is one of the main reasons why pointers are used to access the elements of an array—the code that is generated is generally more efficient. Of course, if access to the array is not generally sequential, pointers accomplish nothing, as far as this issue is concerned, because the expression *(pointer + j) takes just as long to execute as does the expression array[j].
Can someone explain what is faster than what ? Specifically, if speed of array[j] = speed of *(pointer + j) then what is the process of indexing an array and what is the process of accessing the contents of a pointer ? Also, there are questions and answers on SO that mention that array[j] is converted to *(array+j) during compilation so there shouldn't be any difference.
Summary: Please give me a very simple example of what Kochan says. 2 pieces of code and point at faster one, don't have to explain why it is true.
Look at the snippet
int arr[5] = {0};
int *p = arr;
int c = 1;
Now, see the loop 1:
for(int i = 0; i < 5; i++)
arr[i] = c++ + 1;
loop 2:
for(int i = 0; i < 5; i++)
*p++ = c++ + 1;
The difference between these two loops is their body. First loop contains arr[i] = c++ + 1
. This is equivalent to *(arr + i) = c++ + 1
. What does it mean by *(arr + i)
?
It means that:
i
i
to the base address. While in case of second loop's body *p++
means:
p
1
. Of course second one will execute faster. But, now a days modern compilers are smart enough to optimize these codes and most probably you will get the same result for both loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With