问题
How to initialize a global array with -1
values in C
? Please tell me.
回答1:
In C the initialization of a variable is assigning it an initial value so that, even before the program starts its execution, the memory location in which the variable is stored contains the assigned value.
The only way to initialize an array of integers so that all its elements will have a value different to 0 is defining all its element one by one:
int arr[5] = { -1, -1, -1, -1, -1 };
This could be difficult to maintain is the array is big. The alternative is setting values at runtime.
In order to set all elements of a memory area to a specific values, memset
function can be used (it is defined in <string.h>
). It works great for characters:
char arr [100];
memset (arr, -1, sizeof(arr));
If you have integers, just for the value -1, you can use a trick relying on the binary representation of negative values (two's complement): in a -1 all bytes are equal to 0xFF
.
int arr [100];
memset (arr, 0xFF, sizeof(arr));
But unfortunately it's not a general solution If you have different types (eg.structs) or different values (-1 is a particular case) you will have to use a for loop.
Note: there are not particular constraints if the array is global: the initialization is the same and the way of setting the values is the same as well. In runtime scenario, in case of global arrays, you will just want to make sure that every access to the array is performed after its elements have been set to the expected value. This can be obtained, for example, performing the initial sets an a arr_init()
function.
回答2:
Most of the time you would use run-time assignment rather than initialization, with functions like memcpy
or memset
. The only time when run-time assignment can't be done is when the array is supposed to be const
- in such cases you must use initialization instead.
To actually initialize an array to a certain value other than zero, you will have to type out those values explicitly.
If the initializer list is complex, one sound solution is to generate the source code for it with external scripts and then paste the outcome of those into your .c file.
Just for the record, there are also various more or less ugly ways to achieve this with macro tricks, the simplest one being:
#define VAL -1
#define VAL1 VAL, // note the comma here
#define VAL2 VAL1 VAL1
#define VAL5 VAL2 VAL2 VAL1
#define VAL10 VAL5 VAL5
...
const int array[10] = { VAL10 };
which expands to -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
.
This can be made quite variable if taken further into the land of macro insanity, which I really don't recommend:
#define DECLARE_ARRAY(type, name, size) type name[size] = { VAL##size }
...
#undef VAL
#define VAL -2 // change the value to -2 instead
DECLARE_ARRAY(const int, array, 10);
Such macros that attempt to re-invent the language are very bad practice.
来源:https://stackoverflow.com/questions/61743899/how-to-initialize-global-array-with-1