0

I'm asking: is it possible to perform a multiple assignament values after array definition? I performed different tests with different sintax without success.

Here my source code:

#include <stdio.h>

typedef int coords[3];


int main(int argc, char **argv)
{
    coords x = {1, 2, 3};        // it works
    x = {1, 2, 3};               // it doesn't work. Compiler gives the 'error: expected expression before ‘{’ token'
    // x = (int[3]) {1, 2, 3};   // it doesn't work. Compiler gives the 'error: assignment to expression with array type'
    // x = (coords[3]) {1, 2, 3};// it doesn't work. Compiler gives the 'error: assignment to expression with array type'
    // x = (coords) {1, 2, 3};   // it doesn't work. Compiler gives the 'error: assignment to expression with array type'
        
    printf("%d\n", x[0]);
    return 0;
}

Where I'm wrong ?

Thank you

Marco

Naccio
  • 31
  • 7
  • 1
    It is not possible. Arrays in C are second-class citizens, and cannot be assigned. See more at [this answer](https://stackoverflow.com/questions/50808782/what-does-impossibility-to-return-arrays-actually-mean-in-c/50808867#50808867). – Steve Summit Aug 19 '21 at 19:08

2 Answers2

5

is it possible to perform a multiple assignament values after array definition?

No.

It's only during initialization that you can give values to multiple array elements.

Assignments can only be done to a single array element.

Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
3

is it possible to perform a multiple assignament values after array definition?

It is not, but you can do some tricks.

typedef int coords[3];
typedef struct
{
    coords c;
}coords_s;

int main(int argc, char **argv)
{
    coords x = {1, 2, 3};        // it works
    memcpy(x, (coords){4, 5, 6}, sizeof(x)); 

    printf("%d\n", x[0]);

    coords_s cs = {{1, 2, 3}};        
    cs = (coords_s){{6, 5, 4}};
    printf("%d\n", cs.c[0]);

    return 0;
}
0___________
  • 60,014
  • 4
  • 34
  • 74
  • Note that initialization will extend with zeros but memcpy will not, so it is up to the user to provide the correct input. – stark Aug 19 '21 at 20:05