What is the difference between '.' and '->' when used in array? [closed]

Assuming foo is a simple POD user-defined type used in an array, those 2 statements are certainly not the same. As you may know, all the following has the same semantic meaning for the above context:

  *foo
  *(foo + 0)
  foo[0]
  0[foo]

If you take the 2 statements and substitute them with the 3rd form you get:

(*foo)[i].bar ==> foo[0][i].bar

vs

foo[i]->bar ==> (*foo[i]).bar ==> foo[i][0].bar

You can confirm this with a simple test:

#include <stdio.h>
#include <assert.h>

struct foo_t
{
  int bar;
};

int main()
{
    foo_t foo[2][2] = { { {0xdeadbeef}, {0xbadbeef} }, 
                        { {0xbadf00d}, {0xdecafbad} } };

    assert((*foo)[1].bar == foo[0][1].bar);
    assert(foo[1]->bar == foo[1][0].bar);
    assert(foo[1]->bar != (*foo)[1].bar);

    printf("(*foo)[1].bar: %x\n", (*foo)[1].bar);
    printf("foo[1]->bar: %x\n", foo[1]->bar);
}

If they were the same, the 3rd assertion would have failed and the output would not be what it is.

Leave a Comment