简体   繁体   English

C中的整数数组初始化错误

[英]integer array initialization error in C

I'm trying to initialize my array in the following way but get an expression syntax error:我正在尝试按以下方式初始化我的数组,但出现表达式语法错误:

int LineOne[ARRAY_LENGTH];//where ARRAY_LENGTH is a constant of length 10
if(SOME_CONDITION_IS_TRUE){
LineOne[ARRAY_LENGTH] = {0,1,0,0,1,1,1,0,1,1};
}

You cannot have array literals in "classic" C, except as initializers when the variable is being defined.在“经典”C 中不能有数组文字,除非在定义变量时作为初始值设定项。

In C99, you can use compound literals to do this, but you must repeat the type in a cast-like expression before the literal:在 C99 中,您可以使用复合字面量来执行此操作,但您必须在字面量之前在类似强制转换的表达式中重复该类型:

LineOne = (int[ARRAY_LENGTH]) { 0,1,0,0,1,1,1,0,1,1 };

It really depends on the rest of the code (how you want to use the array), what solution is the best.这真的取决于代码的其余部分(你想如何使用数组),什么解决方案是最好的。 One other way to do it could be...另一种方法可能是......

int* LineOne = 0;
if(SOME_CONDITION_IS_TRUE) {
    static int* init = {0,1,0,0,1,1,1,0,1,1};
    LineOne = init;
}

You can not do it that way.你不能那样做。 You could use an alternate array and copy it:您可以使用备用数组并复制它:

#include <string.h>
…
int values[] = {0,1,0,0,1,1,1,0,1,1};

int LineOne[ARRAY_LENGTH];//where ARRAY_LENGHT is a constant of length 10
if(SOME_CONDITION_IS_TRUE)
    memcpy(LineOne, values, sizeof(values));

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

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