2

Not able to initialize the array in sequence. Actually, I want to construct the message with the length of 64. providing 64 array indexes, the code looks longer and verbose. I want to do it in sequence in order to avoid verbosity.


But I initialized an array like this buf[] and I tried as buf[6] also that didn't work either.

error: expected expression before ‘]’ token

Does anyone tell how to do it? Isn't it possible in C to initialize an array in different line not at declaration?


ARRAY_SIZE just give the count of array indexes.

Code:

void a_test(char in) {

    uint8_t buf[256];
    int i;

    char cmd = in;

    if (cmd == 'a') {
        // it doesn't work like this 
        buf[] = { 0xfe, 0xb0, 0x01, 0x22, 0x00, 0x00};

        /* it works like this
        buf[0] = 0xfe;
        buf[1] = 0xb0;
        buf[2] = 0x01;
        buf[3] = 0x22;
        buf[4] = 0x00;
        buf[5] = 0x00; */
    }


    if (cmd == 'b') {
        buf[] = { 0x44, 0xb0, 0x01, 0x03, 0x00};
    }


    for (i = 0; i < ARRAY_SIZE(buf); i++) {
        printf("%02x ", buf[i]);
    }
}

int main() {
  a_test('a');
  return 0;
}
wildpointerxx
  • 459
  • 4
  • 9

2 Answers2

2

You can't use :

buf[] = { 0xfe, 0xb0, 0x01, 0x22, 0x00, 0x00};

except if it is in the declaration e.g:

uint8_t buf[]= { 0xfe, 0xb0, 0x01, 0x22, 0x00, 0x00};

Another way to pass all the values in one statement would be using memcpy:

memcpy(buf, (uint8_t[]) { 0xfe, 0xb0, 0x01, 0x22, 0x00, 0x00 }, sizeof (buf));
coder
  • 12,832
  • 5
  • 39
  • 53
2

Arrays do not have the assignment operator but structures do have. So you can wrap an array in a structure.

That is you can do something like the following.

#include <stdio.h>
#include <stdint.h>

void a_test( char in ) 
{
    struct Array
    {
        size_t n;
        uint8_t buf[256];
    } a = { 0 };        

    switch ( in )
    {
    case 'a':
        a = ( struct Array ) { 6, { 0xfe, 0xb0, 0x01, 0x22, 0x00, 0x00 } };
        break;

    case 'b':
        a = ( struct Array ) { 5, { 0x44, 0xb0, 0x01, 0x03, 0x00 } };
        break;
    }

    for ( size_t i = 0; i < a.n; i++ )
    {
        printf( "%02x ", a.buf[i] );
    }
    putchar( '\n' );
}

int main(void) 
{
    a_test( 'a' );
    a_test( 'b' );

    return 0;
}

The program output is

fe b0 01 22 00 00 
44 b0 01 03 00 
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335