cuziluvtosmile
cuziluvtosmile

Reputation: 47

Pointer to an array of int pointers in C

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!

Upvotes: 3

Views: 424

Answers (3)

*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)

Upvotes: 1

fuz
fuz

Reputation: 92966

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.

Upvotes: 5

Joseph Young
Joseph Young

Reputation: 2795

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.

Upvotes: 2

Related Questions