1

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};
}

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You cannot have array literals in "classic" C, except as initializers when the variable is being defined.

In C99, you can use compound literals to do this, but you must repeat the type in a cast-like expression before the literal:

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

4 Comments

any other way I can initialize the array like above?
@user1870194 memset(), memcpy(), etc. or manual one-by-one initialization. Sorry, but much data is much.
Just keep in mind that using direct memory access is prone to byte order issues when porting to other platforms.
thanks a million people :) i think @kotlinski answered my question
0

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));

3 Comments

@carlosdc No. sizeof(values) is the numbr of bytes of the whole values array.
the values {0,1,0,0,1,1,1,0,1,1} are dynamically changing values based on a condition and this is the reason why I want to initialize LineOne[ArrayLength] later in the code. Any other way? Right now what I'm doing is:codeif(SOME_CONDITION){LineOne[i] = 1; i++; LineOne[i] = 0; i++; LineOne[i] = 1; i++; LineOne[i] = 1; i++; LineOne[i] = 1; i++; LineOne[i] = 1; i++; LineOne[i] = 1; i++; LineOne[i] = 0; i++; LineOne[i] = 0; i++; LineOne[i] = 1;}code
@user1870194 it is very dependant on how you acquire the values {0,1,0,0,1,1,1,0,1,1}. If they are in an array then you can memcpy the array. Otherwise chances are you will have to make element by element assignement. Note that not using i as an index but an actual literal (0, etc.) is easier.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.