简体   繁体   English

在typedef结构中填充int数组时出错

[英]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: 我试图在Huffman结构中初始化代码数组,但是在编译时显示:

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; //WORKSline[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}; //Wrongline[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. Statement2表示与编译器类似的内容:转到名为line[2]结构数组,然后选择元素数组code转到其10个元素,这是错误的,因为仅为8个整数值保留了内存,但由于C中没有绑定检查,所以完全正确,然后在其中粘贴一个{0,0,1,0,1}元素,这是不可能的,因为您需要将这些值粘贴到该元素。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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