In the code below could somebody explain why sum += *(ptr+i);
is the same as sum += ptr[i];
?
I understand that sum += *(ptr+i);
is dereferencing the memory address and then summing the numbers?
But in sum += ptr[i];
there is no deference...
#include <stdio.h>
#include <stdlib.h>
int main() {
int len, i, sum;
printf("Enter how many numbers you want to sum:");
scanf("%d", &len);
int* ptr;
ptr = (int*)malloc(sizeof(int) * len);
for(i=0; i < len; i++) {
printf("Enter a number:");
scanf("%d", ptr+i);
}
for(i=0; i < len; i++) {
//sum += *(ptr+i);
sum += ptr[i];
}
printf("The sum is %d", sum);
return 0;
}
By the definition (the C Standard, 6.5.2.1 Array subscripting)
2 A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).
Thus these three statements
sum += *(ptr+i);
sum += ptr[i];
sum += i[ptr];
are equivalent.
Take into account that the program has undefined behavior because the variable sum
was not initialized.:) To avoid an overflow it would be better to declare it like
long long int sum = 0;
// ...
printf("The sum is %lld\n", sum);
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