0

I am trying to understand how pointers work and I am stuck on this block of code. Can someone explain where does the expression '*(a+tally)' point to in this block of code? What is the logic behind it?

#include <stdio.h>
int main()
{ 
    int a[5]={1,2,3,4,5},b[5]={10,20,30,40,50},tally;
    
    for(tally=0;tally< 5;++tally)
    {
        *(a+tally)= *(tally+a) + *(b+tally);
    }
    
    for(tally=0;tally< 5;tally++) 
    {
        printf("%d" *(a+tally));
    }
    
    return 0;
}
Kira_99
  • 3
  • 3
  • 3
    is this easier to read? `a[tally] += b[tally];` – Michael Dorgan Oct 23 '20 at 18:00
  • 1
    Related: [Are arrays in C a syntactic sugar for pointers? - Stack Overflow](https://stackoverflow.com/questions/48851598/are-arrays-in-c-a-syntactic-sugar-for-pointers) – MikeCAT Oct 23 '20 at 18:01
  • The expression `*(a+tally)` does not point to anything. The expression `a + tally` is the address of an element of `a`, and `*(a + tally)` is the object at that address. `a` has 5 elements. `a + 0` is the address of the first, `a + 1` is the address of the next, etc. `a + (i - 1)` is the address of the ith element. So `a + 4` is address of the 5th element. – William Pursell Oct 23 '20 at 18:08

1 Answers1

1

For example this expression

*(a+tally)

is equivalent to the expression

a[tally]

and yields the (lvalue) element of the array at index tally.

As a result this loop

for(tally=0;tally< 5;++tally)
{
    *(a+tally)= *(tally+a) + *(b+tally);
}

is equivalent to the following loop

for(tally=0;tally< 5;++tally)
{
    a[tally] = a[tally] + b[tally];
}

That is the expression

a + tally

or the equivalent expression

tally + a

points to the element of the array a with the index equal to the value of tally.

Pay attention that as the expression a[tally] is calculated like *( a + tally ) or as *( tally + a ) (due to the commutative nature of the addition) then the expression a[tally] may be rewritten also like tally[a].

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • `tally[a]` : I never seen this before, it's so strange.. Thanks for the info anyway ! – dspr Oct 23 '20 at 18:39