-1

in c, when allocating a new dynamic memory with malloc:

int* x = (int*)malloc(sizeof(x));
int y = 10;

is this line:

*x = y;

equal to this line:

x[0] = y;
GuyB
  • 3
  • 5
  • 5
    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
  • 2
    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? – avans 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

4

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
  • 174,148
  • 38
  • 234
  • 367