-1

I am confused about C syntax. If I allocate memory:

int* x = (int*)malloc(1 * sizeof(int));

Are these two code snippets of an int pointer equal?

*x = 0;

And

x[0] = 0;
GuyB
  • 30
  • 8
  • 6
    Yes, it is equal. – Devolus Apr 08 '21 at 12:52
  • 4
    Note that `sizeof(x)` is not necessarily the correct size to allocate space for an `int` because `x` is a pointer and, in some implementations sizeof a pointer is different to sizeof an int. Use `int *x = malloc(sizeof *x);` (with no redundant cast, remember to `#include `) – pmg Apr 08 '21 at 12:54
  • 3
    More generally `*(x+y)` is strictly the same as `x[y]`. – Jabberwocky Apr 08 '21 at 12:55
  • @Jabberwocky: or `y[x]`... *3["foobar"] == "foobar"[3] == \*(3 + "foobar") == 'b'* – pmg Apr 08 '21 at 12:57
  • 1
    And more interestingly it's the same as `0[x] = y;`. – anastaciu Apr 08 '21 at 13:02
  • @anastaciu: Can you explain why it is more interesting other than _it's good to know_ ? Are there some usecases for it? – Wör Du Schnaffzig Apr 08 '21 at 13:13
  • @pqans, when I first realized this could be done I though it was interesting at the time, explanations are plentiful in the platform, a simple search renders you several results, but realizing that `*(0 + x)` is the same as `0[x]` kind of explains itself. – anastaciu Apr 08 '21 at 13:21
  • Wrong size: `int* x = (int*)malloc(sizeof(x));` --> `int* x = malloc(sizeof *x);` – chux - Reinstate Monica Apr 08 '21 at 17:24

1 Answers1

5

The definition of the [] operator is: given ex1[ex2], it is guaranteed to be equivalent to

*((ex1) + (ex2))

Where ex1 and ex2 are expressions.

In your case x[0] == *(x + 0) == *(x) == *x.

See Do pointers support "array style indexing"? for details.

Lundin
  • 195,001
  • 40
  • 254
  • 396