Declaring and initializing arrays in C

Is there a way to declare first and then initialize the array in C?

So far, I have initialized such an array:

int myArray[SIZE] = {1,2,3,4....}; 

But I need to do something like this

 int myArray[SIZE]; myArray = {1,2,3,4....}; 
+47
c arrays initialization
Jun 29
source share
8 answers

In C99, you can do this using a complex literal combined with memcpy

 memcpy(myarray, (int[]) { 1, 2, 3, 4 }, sizeof myarray); 

(provided that the size of the source and the size of the target are the same).

In C89 / 90, you can emulate this by declaring an additional "source" array

 const int SOURCE[SIZE] = { 1, 2, 3, 4 }; /* maybe `static`? */ int myArray[SIZE]; ... memcpy(myarray, SOURCE, sizeof myarray); 
+27
Jun 29 '10 at 3:40
source share

No, you cannot set them to arbitrary values ​​in one expression (unless this is done as part of the declaration).

You can do this with code, for example:

 myArray[0] = 1; myArray[1] = 2; myArray[2] = 27; : myArray[99] = -7; 

or (if there is a formula):

 for (int i = 0; i < 100; i++) myArray[i] = i + 1; 

Another possibility is to store some templates installed during the declaration and use them to initialize the array, for example:

 static const int onceArr[] = { 0, 1, 2, 3, 4,..., 99}; static const int twiceArr[] = { 0, 2, 4, 6, 8,...,198}; : int myArray[7]; : memcpy (myArray, twiceArr, sizeof (myArray)); 

This has the advantage (most likely) faster and allows you to create smaller arrays than templates. I used this method in situations where I need to reinitialize the array quickly, but in a specific state (if all zeros were in the state, I would just use memset ).




You can even localize it using the initialization function:

 void initMyArray (int *arr, size_t sz) { static const int template[] = {2, 3, 5, 7, 11, 13, 17, 19, 21, ..., 9973}; memcpy (arr, template, sz); } : int myArray[100]; initMyArray (myArray, sizeof(myArray)); 

A static array will (almost certainly) be created at compile time, so there will be no runtime overhead, and memcpy should be dazzlingly fast, probably faster than the 1,229 assignment operators, but it’s very less likely to type your role :-).

+13
Jun 29 '10 at 3:44
source share

Is there a way to declare the first and then initialize the array in C?

There is! but not using the method you described.

You cannot initialize a comma-separated list; this is only allowed in the declaration. However, you can initialize with ...

 myArray[0] = 1; myArray[1] = 2; ... 

or

 for(int i = 1; i <= SIZE; i++) { myArray[i-1] = i; } 
+4
Jun 29 2018-10-06T00:
source share

This is an addition to the accepted AndreyT answer with Nyan's comments about inappropriate array sizes. I do not agree with their automatic setting of the fifth element to zero. It will probably be 5 - the number after 1,2,3,4. Therefore, I suggest the memcpy () shell to create a compile-time error when trying to copy arrays of different sizes:

 #define Memcpy(a,b) do { /* copy arrays */ \ ASSERT(sizeof(a) == sizeof(b) && /* a static assert */ \ sizeof(a) != sizeof((a) + 0)); /* no pointers */ \ memcpy((a), (b), sizeof (b)); /* & unnecesary */ \ } while (0) /* no return value */ 

This macro will generate a compile-time error if your array has a length of 1. This is possibly a function.

Since we use a macro, the C99 compound literal requires an extra pair of parentheses:

 Memcpy(myarray, ((int[]) { 1, 2, 3, 4 })); 

Here ASSERT () is a "static statement". If you don't have your own yet, I use the following on multiple platforms:

 #define CONCAT_TOKENS(a, b) a ## b #define EXPAND_THEN_CONCAT(a,b) CONCAT_TOKENS(a, b) #define ASSERT(e) enum {EXPAND_THEN_CONCAT(ASSERT_line_,__LINE__) = 1/!!(e)} #define ASSERTM(e,m) /* version of ASSERT() with message */ \ enum{EXPAND_THEN_CONCAT(m##_ASSERT_line_,__LINE__)=1/!!(e)} 
+2
Jun 30 '10 at 14:29
source share

Why can't you initialize when declaring?

Which C compiler are you using? Does it support C99?

If it supports C99, you can declare the variable where you need it and initialize it when you declare it.

The only excuse I can think of because I am not doing this would be because you need to declare it, but make an early exit before using it, so the initializer will be wasted. However, I suspect that any such code is not as carefully organized as it should be, and it could be written so that this is not a problem.

+1
Jun 29 2018-10-06T00:
source share

There is no such specific way in which you can initialize an array after declaring it once.

Only three options:

1.) initialize them in different lines:

 int array[SIZE]; array[0] = 1; array[1] = 2; array[2] = 3; array[3] = 4; //... //... //... 

But that is not what you want, I think.

2.) Initialize them using a for or while loop:

 for (i = 0; i < MAX ; i++) { array[i] = i; } 

This is the BEST WAY to achieve your goal.

3.) If you need to initialize an array in one line, you must define at least an array with initialization. And then copy it to your target array, but I think there is no use to it, in this case you have to define and initialize your array in one line.

And may I ask you why exactly you want to do this?

0
Jun 29 2018-10-06T00:
source share

The OP left some important information from the question and only put it in a comment on the answer.

I need to initialize after the declaration, because it will differ depending on the condition, I mean something like this int tuAggau [SIZE]; if (condition1) {myArray {x1, x2, x3, ...}} else if (condition2) {myArray {y1, y2, y3, ...}}., and so on ...

Given this, all possible arrays must be stored somewhere in the data, so memcpy is not required (or not required), only a pointer and a 2d array are required.

 //static global since some compilers build arrays from instruction data //... notably not const though so they can later be modified if needed #define SIZE 8 static int myArrays[2][SIZE] = {{0,1,2,3,4,5,6,7},{7,6,5,4,3,2,1,0}}; static inline int *init_myArray(_Bool conditional){ return myArrays[conditional]; } // now you can use: //int *myArray = init_myArray(1 == htons(1)); //any boolean expression 

The non-native version gives this resulting assembly on x86_64:

 init_myArray(bool): movzx eax, dil sal rax, 5 add rax, OFFSET FLAT:myArrays ret myArrays: .long 0 .long 1 .long 2 .long 3 .long 4 .long 5 .long 6 .long 7 .long 7 .long 6 .long 5 .long 4 .long 3 .long 2 .long 1 .long 0 

For additional conditional expressions / arrays, just change 2 in myArrays to the desired number and use the same logic to get a pointer to the right array.

0
Jan 09 '17 at 5:44
source share

It is not possible to immediately assign values ​​to an array immediately after initialization. A better alternative would be to use a loop.

 for(i=0;i<N;i++) { array[i] = i; } 

You can hard code and assign values, such as - array[0] = 1 , etc.

Memcpy can also be used if you already have data stored in an array.

0
Jun 28 '17 at 17:06 on
source share



All Articles