简体   繁体   中英

Error filling an int array in a typedef struct

I tried to initialize the code array in Huffman struct but when i compiled it showed:

Error expected expression before '{' token.
How I can fix it?

typedef struct {  
    char letter;  
    float p;  
    int code[10];  
    }Huffman ;  
    Huffman line[4];   

    line[1].code[10]= {1,0,0,0};  
    line[2].code[10]= {0,0,1,0,1};  
    line[3].code[10]= {1,0,0,0,0};

Error : The Error is due to way of initialization.

Statement1: line[1].code[1] = 10; //WORKS line[1].code[1] = 10; //WORKS
Statement2: line[2].code[10]= {0,0,1,0,1}; //Wrong line[2].code[10]= {0,0,1,0,1}; //Wrong

The Statement2 says something similar to compiler: Go to Structure Array named as line[2] and select element array code go to its 10 element which is wrong as only memory is reserved for 8 integer values but since there is no bound checking in C so that its terribly OK and paste an {0,0,1,0,1} element there, which is not possible as you are pasting these values to that one element.

Better Approach

   //Declaring variable SIZE thus prevent BOUND CHECKING.
     int size;        
     size = sizeof(line[1].code)/sizeof(line[0].code[0])); //COUNTING NO OF ELEMENTS
     for (loop = 0; loop<size; loop++)
         line[1].code[loop] = loop;            //INITIALING BY Values 0,1,2,3,4.... 

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