-1

Recently, I found an interesting code snippet about array and pointers I didn't understand as a whole.

Here's the code:

void Function(int *B, int *A, int *C, int m)
{
   int i;
   A++;
   for(i = 0; i < m; i++, B++, A++, C++)
    *C=*B + *(A-1);
}

int main()
{
  int A[] = {3,6,2};
  int B[] = {5,7,9};
  int C[3];
  int n = 3;
  int i;
  
  Function(A,B,C,n);
  for(i = 0; i < n; i++)
  printf("%d ",C[i]);
  return 0;


}

Okay, so, in the main, we have two arrays, variable n which we're forwarding to the function. *B, *A, *C are pointers to the first element of an array. First, we have A++, which means that now, A shows on the second element of an array, which is 7. In the first for loop, i = 0, then *C(first element) = 3 + 5 = 8

Then, i = 1, B is now pointing on 6, A on 9.

Next, the second for loop looks like this: *C(second element) = 6 + 7 = 13 Till this part, i understood. Now, i incremented to 2, B is showing on 2, but then, we have A++ again, but how A will increment when there is no other element in that array, it's blank basically? When i debugged, in third for loop, A will be 9(A-1), but again, not completely sure how that work.

alinsoar
  • 15,386
  • 4
  • 57
  • 74
  • 1
    Accessing an array out of bounds results in undefined behaviour. Most of the time it will just read whatever is in memory. – Jabberwocky Feb 09 '22 at 09:22
  • 1
    The `A++` before the loop cancels the `(A-1)` inside the loop. So pointer `A` isn't doing anything different than pointer `B`. – user3386109 Feb 09 '22 at 09:23
  • The code (especially the inconsistent order of ABC) is intentionally obfuscated. What is the reason for you to dig into it? – Yunnosch Feb 09 '22 at 09:25

1 Answers1

0

It's ok to increment a pointer to just past the last element in an array. With such a pointer, you can't dereference it or increment it again (it's undefined behavior).

C is very specific about what you can do with pointer arithmetic without causing undefined behavior, for example disallowing decrementing a pointer to before the first element of the array, or having the pointer increment after the array except for just after the final element. If you have a single object pointed to (rather than an array), it's treated as an array of length 1 for these rules.

Paul Hankin
  • 54,811
  • 11
  • 92
  • 118