3

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!

2
  • 1
    Why do you avoid index expressions? Please remember that a[b] is defined to be equal to *(a + b). Commented Dec 20, 2015 at 21:48
  • I understand it's clearer with subscripting, but I wanted to get my head around pointers. Commented Dec 20, 2015 at 22:07

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

1 Comment

@NidhiKantak It's a pleasure to me.
2

score_cards points to the first element of the array, *score_cards is the first element of the array.

Pointer arithmetic is aware of sizes and therefore is not required to be scaled to the size of the type.

Comments

1

*score_card doesn't point to the the first element of the array - it is the first element of the array. So *score_card + 5 will be the first element of the array plus five - not the 6th element of the array.

When you add a number to a pointer, the compiler automatically multiplies the number by the size of the thing being pointed to. So score_card + i "actually" means score_card + i*sizeof(*score_card). (Of course, if you wrote that in the program, it would end up acting like score_card + i*sizeof(*score_card)*sizeof(*score_card) which isn't what you want)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.