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?

1
  • 2
    Is memcpy suitable for you? or memset if you want to set to all zero. Commented Dec 15, 2015 at 0:09

1 Answer 1

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));  
Sign up to request clarification or add additional context in comments.

2 Comments

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.
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 structs). 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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.