Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

understanding the difference between pointer dereference and array indexing

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;
}
like image 709
artic sol Avatar asked Oct 15 '25 16:10

artic sol


1 Answers

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);
like image 92
Vlad from Moscow Avatar answered Oct 17 '25 05:10

Vlad from Moscow