0
// Program to calculate the sum of n numbers entered by the user

#include <stdio.h>
#include <stdlib.h>

int main() {
  int n, i, *ptr, sum = 0;

  printf("Enter number of elements: ");
  scanf("%d", &n);

  ptr = (int*) malloc(n * sizeof(int));
 
  // if memory cannot be allocated
  if(ptr == NULL) {
    printf("Error! memory not allocated.");
    exit(0);
  }

  printf("Enter elements: ");
  for(i = 0; i < n; ++i) {
    scanf("%d", ptr + i);
    sum += *(ptr + i);
  }

  printf("Sum = %d", sum);
  
  // deallocating the memory
  free(ptr);

  return 0;
}

I was reading this example in an internet tutorial, and I didn't understand why ptr+i was used inside the for loop. Could someone explain to me the meaning of using a "+" sign between the pointer and this entire variable?

scanf("%d", ptr + i);
sum += *(ptr + i);
kopew
  • 41
  • 5
  • 6
    `ptr + i` is equivalent to `&ptr[i]`, and consequently `*(ptr + i)` is equivalent to `ptr[i]`. – Eugene Sh. May 31 '22 at 22:23
  • 1
    In fact (IIRC), the C Standard actually states that `ptr[i]` is syntactically equivalent to `*(ptr + i)`. – Adrian Mole May 31 '22 at 22:32
  • these pointers are confusing me a lot.. do you know of any material for beginners that explains pointers well and in a simple way?? – kopew May 31 '22 at 22:34
  • 1
    @kopew You may use even three signs + between an integer and a pointer as for example for(i = 0; i < n;) { scanf("%d", i +++ ptr); } – Vlad from Moscow May 31 '22 at 22:36
  • @VladfromMoscow Hehe. – Adrian Mole May 31 '22 at 22:38
  • 1
    Perhaps [What are the barriers to understanding pointers and what can be done to overcome them?](https://stackoverflow.com/questions/5727/what-are-the-barriers-to-understanding-pointers-and-what-can-be-done-to-overcome) – Weather Vane May 31 '22 at 22:42
  • 1
    Thanks @WeatherVane - I've delete my comment as I wasn't looking at this correctly. – stdunbar May 31 '22 at 22:55
  • @AdrianMole: The standard says `ptr[i]` is **semantically** equivalent to `*(ptr + i)`, or, more specifically, `E1[E2]` is semantically equivalent to `(*((E1)+(E2)))`. Syntactically, they are different. Syntax is about relationships between “symbols” (essentially tokens of the C grammar). Semantics is about meaning. `ptr[i]` means the same thing as `*(ptr + i)`, but it has different tokens that are parsed differently. – Eric Postpischil Jun 01 '22 at 00:15

1 Answers1

0

Notice that *(ptr+i)==ptr[i] because the meaning of *(ptr) in term of memory address is the beginning of the array adress in the memory i.e. the first element of the array. Therefore *(ptr) is equivalent to ptr[0]. Anyway, the addition of i to *(ptr) moves on the array elements i elements foward to the i element in your array.

DorI
  • 22
  • 6