Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assign an array to another

Tags:

c

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.

like image 400
Valentin Lorentz Avatar asked Jun 02 '12 13:06

Valentin Lorentz


2 Answers

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

coordinates coord2;

memcpy(coord2, coord, sizeof coord2);
like image 133
ouah Avatar answered Sep 20 '22 05:09

ouah


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.

like image 27
Sergey Kalinichenko Avatar answered Sep 21 '22 05:09

Sergey Kalinichenko