简体   繁体   中英

structure errror in C error: expected identifier or ‘(’ before ‘.’ token

#include <stdio.h>

typedef struct car{

    unsigned char buf[1024];
    int index;
    int hdr;
    int len;
    int dlms_detected;

}frma ;

    int main()
    {
        frma dms;
        dms.buf[1024] = {0x21,0x01,0x12,0x00};
        dms.len  = ( (dms.buf[3] << 8 ) | dms.buf[2] );
        printf("%d",dms.len);
        return 0;
    }

I compiled the above code and got the below error

main.c:20:17: error: expected expression before ‘{’ token
   20 | dms.buf[1024] = {0x21,0x01,0x12,0x00};

I have declared structure and has given semicolon for every line still getting the error,someone pls tell me where I did wrong?

Firstly the assignment operator is not defined for arrays in C. And secondly this expression dms.buf[1024] having the type unsigned char is trying to access memory beyond the declared array So this statement

    dms.buf[1024] = {0x21,0x01,0x12,0x00};

is incorrect.

You could initialize the array when the object dms is declared as for example

    frma dms =
    {
        .buf = {0x21,0x01,0x12,0x00}
    };
    dms.len  = ( (dms.buf[3] << 8 ) | dms.buf[2] ); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM