title: How to initialize an array in c?
body: <p>I have a function that should initialize an array of length 3 and return it. See the code below. It's working so far but only for certain colors. I recognized a bug in my code when I tried to write violet. I got a trailing orange element when I write violet. Why is that and how can I fix it? I have more color arrays like this defined and some of them seem to "leak" colors. I guess there's something wrong how I initialize the arrays. Hope someone can shed some light into this.</p>
  
  <pre><code>#define LEDS 64
  
  struct array{ unsigned char hex[LEDS * 3]; };
  
  struct array init_array(int r, int g, int b) {
      int i;
      struct array z;
      //GRB data, 3 bits for each color
      for(i = 0; i &lt; sizeof(struct array) / sizeof(char); i++) {
          if(i == 0) z.hex[i] = g | 128;
          else if(i==1) z.hex[i] = r | 128;
          else z.hex[i] = b | 128;
      }
      return z;
  }
  ...
  struct array orange;
  struct array violet;
  ...
  violet=init_array(173, 141, 171); 
  orange=init_array(192, 145, 128); 
  
  while(1) {
      for(i=0; i&lt;=LEDS; i++) {
          transfer(fd, violet.hex, sizeof (violet.hex));
      }
      for(i=0; i&lt;=LEDS; i++) {
          transfer(fd, orange.hex, sizeof (orange.hex));
      }
  }
  </code></pre>
  
  <p>That's the transfer function:</p>
  
  <pre><code>void transfer(int fd, char* tx, uint32_t len) {
      int ret; 
      uint8_t rx[sizeof (&amp;tx)] = {0,}; // RX buffer
  
      struct spi_ioc_transfer data = {
          .tx_buf = (unsigned long) tx,
          .rx_buf = (unsigned long) rx,
          .len = len,
          .delay_usecs = delay,
          .speed_hz = speed,
          .bits_per_word = bits,
          .cs_change = 0,
      };
  
      ret = ioctl(fd, SPI_IOC_MESSAGE(1), &amp;data);
      if (ret &lt; 1)
          pabort("can't send spi message");
  
      usleep(50);
  }
  </code></pre>