0
  int zero[5][4] = {
    { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }
  };
  int m1[5][4] = {
    { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 }
  };

  //errors here
  m1 = zero;
  m1 = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 }, { 0, 0, 0, 0 } };
  m1[0] = { 0, 0, 0, 0 };

Is there no syntax for this? Do I have to use a loop with indexing to achieve this?

Maik Klein
  • 15,548
  • 27
  • 101
  • 197
  • 2
    Is [`memcpy`](http://linux.die.net/man/3/memcpy) suitable for you? or [`memset`](http://linux.die.net/man/3/memset) if you want to set to all zero. – kaylum Dec 15 '15 at 00:09

1 Answers1

4

In C, arrays are not assignable or can't be on the left side of assignment (=) operator. Use memcpy.

memcpy(m1, zero, sizeof(zero)); // Assuming size of 'm1' is no less than the size of 'zero'  

You can use memset to set an array with a constant value like 0 or -1

memset(m1, 0, sizeof(m1));  
haccks
  • 104,019
  • 25
  • 176
  • 264
  • http://port70.net/~nsz/c/c11/n1570.html#7.24.6.1p2 `memset` takes basically an `unsigned char`, so you must not use `-1`. Also one should clarify that any other value than `0` is implementation defined - at best, because `memset` does not care about the datatype of the target. It just writes bytes. – too honest for this site Dec 15 '15 at 03:16
  • I don't see the point. It still is implementation defined for negative values. And there already have been quite some questions/problems on SO where the poster thought `memset` would know the type of the array (the problem arises less for `struct`s). My claim stands: except for `char []`, `memset` is only useful to zero an array and even that is questionable for types other than integers, because only for these "all bits 0" really means the value `0`. There is no requirement for e.g. a _null pointer_ to have all bits cleared, nor for a float to interpret that as `0.0`. – too honest for this site Dec 15 '15 at 11:19