9

I have a problem assigning an array like:

int a[];
int b[] = {1,2,3};
&a = &b;

I know I could use pointers but I want to try it that way...

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Starfighter911
  • 197
  • 2
  • 3
  • 9

2 Answers2

21

You can't assign arrays in C. You can copy them with the memcpy() function, declared in <string.h>:

int a[3];
int b[] = {1,2,3};

memcpy(&a, &b, sizeof a);
caf
  • 233,326
  • 40
  • 323
  • 462
  • 2
    @Jonathan Leffler: The `&array` is a deliberate choice - when copying a single object (here, a single array), I think the form `memcpy(&dest, &src, sizeof src)` should be preferred (or with `sizeof dest` - they should be the same). This is for consistency - the same `memcpy()` line would work if the type of `a` and `b` were a non-array type. You may not agree, but hopefully you can see that there is certainly "judgement" behind the choice. – caf Nov 17 '14 at 11:59
  • @weberc2: It is, and `sizeof a` is the size of the array. – caf Feb 14 '15 at 06:27
  • Why does it need a pointer to a pointer? Isn't it enough to have a pointer to the array? – weberc2 Feb 14 '15 at 13:37
  • @weberc2: There is no pointer to a pointer anywhere in that answer. `&a` *is* a pointer to the array, as you said yourself. – caf Feb 14 '15 at 22:43
  • @caf I think you misunderstood me, I said `a pointer to a pointer to an array`, to which you replied, `it is`. But thank you for clarifying, I understand now. – weberc2 Feb 14 '15 at 23:53
  • @weberc2: Ahh yes, you're right - I misread your comment. `&a` is just a pointer to the array. – caf Feb 15 '15 at 05:05
17

That way doesn't work, as you have found. You cannot assign arrays in C.

Structs, however, are assignable. So you can do this:

typedef struct
{
    int x[3];
} T;

T a;
T b = { { 1, 2, 3 } };

a = b;
Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680