5

I tried through different ways to copy an array pointer to another one, without any success. Here are my attempts, with the associated error message.

typedef long int coordinate;
typedef coordinate coordinates[3];

void test(coordinates coord) {
    coordinates coord2 = coord; // error: invalid initializer
    coordinates coord3;
    coord3 = coord; // error: incompatible types when assigning to type ‘coordinates’ from type ‘long int *’
    coord3 = (coordinates) coord; // error: cast specifies array type
    coord3 = (coordinate[]) coord; // error: cast specifies array type
    coord3 = (long int*) coord; // error: incompatible types when assigning to type ‘coordinates’ from type ‘long int *’
}

I know I could use typedef coordinate* coordinates; instead, but it does not look very explicit to me.

Valentin Lorentz
  • 8,859
  • 5
  • 42
  • 63

4 Answers4

5

You cannot assign arrays in C. Use memcpy to copy an array into another.

coordinates coord2;

memcpy(coord2, coord, sizeof coord2);
ouah
  • 134,166
  • 14
  • 247
  • 314
  • At first, I was looking for a way to keep the same data, but only copy the pointer. However, it now looks clearly better to copy data. Thank you for the tip and the code. – Valentin Lorentz Jun 02 '12 at 13:20
  • @valentinLorentz of course if you don't *need* to copy the data, working with pointers would be more efficient. – ouah Jun 02 '12 at 13:21
1

When arrays are passed by value, they decay to pointers. The common trick to work around that is wrapping your fixed-size array in a struct, like this:

struct X {
    int val[5];
};

struct X a = {{1,2,3,4,5}};
struct X b;
b = a;
for(i=0;i!=5;i++)
    printf("%d\n",b.val[i]);

Now you can pass your wrapped arrays by value to functions, assign them, and so on.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399
0

Your coordinates need to be initialized as pointers

coordinates *coords2, *coords3;

Try that out and then assign.

Rishi Diwan
  • 316
  • 1
  • 9
0

You cannot assign one array to another using the assignment operator, e.g. a = b, because an array doesn't know the size of itself.

This is the reason why we cannot assign one array to another using the assignment operator.

Adrian Mole
  • 30,672
  • 69
  • 32
  • 52
Raman Sharma
  • 171
  • 2
  • 10