I am a bit confused in accessing elements in an array of pointers. Say I have an pointer int **score_cards and it points to an array of int pointers of size n. I want to find the sum of the integers pointed to by the elements of the array.
I was thinking of doing:
int sum = 0;
int i;
for(i = 0;i<n;i++){
sum = sum + *(*score_card+ i);
}
But this is wrong, while, the following is right:
int sum = 0;
int i;
for(i = 0;i<n;i++){
sum = sum + *(*(score_card + i));
}
Now, I have two questions, since *score_cards points to the first element of the array, isn't the ith element *score_cards + i? i.e the address of the first element + i? Also, why do we increment i by 1, and not sizeof(*int) ? Thanks in advance!
Please remember that the shorthand syntax a[b] exists for *(a + b) and is exactly equal. You shouldn't use the latter as it's somewhat illegible.
since *score_cards points to the first element of the array
That's incorrect. score_cards points to the first element of the array, *score_cards is the first element of the array. Thus the i-th element of the array is *(score_cards + i) or equally score_cards[i].
Also, why do we increment i by 1, and not sizeof(*int)?
In C, when adding an integer to a pointer, the integer is implicitly multiplied by the size of the type pointed to. This is so that when a is an array of objects of some type, a[i] is the i-th element of that array.
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