How to initialize all members of an array to the same value?
Unless that value is 0 (in which case you can omit some part of the initializer
and the corresponding elements will be initialized to 0), there's no easy way.
Don't overlook the obvious solution, though:
int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
Elements with missing values will be initialized to 0:
int myArray[10] = { 1, 2 }; // initialize to 1,2,0,0,0...
So this will initialize all elements to 0:
int myArray[10] = { 0 }; // all elements 0
In C++, an empty initialization list will also initialize every element to 0.
This is not allowed with C until C23:
int myArray[10] = {}; // all elements 0 in C++ and C23
Remember that objects with static storage duration will initialize to 0 if no
initializer is specified:
static int myArray[10]; // all elements 0
And that "0" doesn't necessarily mean "all-bits-zero", so using the above is
better and more portable than memset(). (Floating point values will be
initialized to +0, pointers to null value, etc.)
Array initialization C
Yes, it's equivalent with the version without the trailing comma.
See this question for more discussion about trailing commas.
Initialize all elements of C array to an integer
Use a loop to assign the desired value to each elements. In typical current computer and compiler with optimization enabled, the cost of memory access should be higher than the cost of looping, so you should only consider the cost of looping only after you actually found it is too slow.
#include <stdio.h>
int main() {
int A[10];
for (size_t i = 0; i < sizeof(A) / sizeof(*A); i++) {
A[i] = -2;
}
printf("%d",A[3]);
}
Initializing array of structures
There's no "step-by-step" here. When initialization is performed with constant expressions, the process is essentially performed at compile time. Of course, if the array is declared as a local object, it is allocated locally and initialized at run-time, but that can be still thought of as a single-step process that cannot be meaningfully subdivided.
Designated initializers allow you to supply an initializer for a specific member of struct object (or a specific element of an array). All other members get zero-initialized. So, if my_data
is declared as
typedef struct my_data {
int a;
const char *name;
double x;
} my_data;
then your
my_data data[]={
{ .name = "Peter" },
{ .name = "James" },
{ .name = "John" },
{ .name = "Mike" }
};
is simply a more compact form of
my_data data[4]={
{ 0, "Peter", 0 },
{ 0, "James", 0 },
{ 0, "John", 0 },
{ 0, "Mike", 0 }
};
I hope you know what the latter does.
How to initialize only few elements of an array with some values?
Is it possible to skip this values and only assign the values 1, 2 and 3?
In C, Yes. Use designated initializer (added in C99 and not supported in C++).
int array[12] = {[0] = 1, [4] = 2, [8] = 3};
Above initializer will initialize element 0
, 4
and 8
of array array
with values 1
, 2
and 3
respectively. Rest elements will be initialized with 0
. This will be equivalent to
int array[12] = {1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0};
The best part is that the order in which elements are listed doesn't matter. One can also write like
int array[12] = {[8] = 3, [0] = 1, [4] = 2};
But note that the expression inside [ ]
shall be an integer constant expression.
C char array initialization: what happens if there are less characters in the string literal than the array size?
This is not how you initialize an array, but for:
The first declaration:
char buf[10] = "";
is equivalent to
char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
The second declaration:
char buf[10] = " ";
is equivalent to
char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};
The third declaration:
char buf[10] = "a";
is equivalent to
char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};
As you can see, no random content: if there are fewer initializers, the remaining of the array is initialized with 0
. This the case even if the array is declared inside a function.
Is there an alternative to Range Initialization of arrays in C?
Code needs to explicitly initialize the non-zero array elements.
Could use macro magic if there is a pattern:
#define ONE(x) (x), (x)+1, (x)+2, (x)+3, (x)+4, (x)+5, (x)+6, (x)+7, (x)+8, (x)+9
#define TEN(x) ONE(x),ONE((x)+10),ONE((x)+20),ONE((x)+30),ONE((x)+40), \
ONE((x)+50),ONE((x)+60),ONE((x)+70),ONE((x)+80),ONE((x)+90)
int main() {
int count[100] = { TEN(1) };
printf("%d %d\n", count[0], count[99] );
}
Output
1 100
Example for OP
#define X2(x) (x), (x)
// Note the nested macro
#define X4(x) X2(x), X2(x)
#define X8(x) X4(x), X4(x)
#define X10(x) X8(x), X2(x)
#define X16(x) X8(x), X8(x)
// ....
int main()
{
int my_array[10] = { X4(5), X4(15), X2(30)};
printf("%d %d\n", my_array[0], my_array[9] );
return 0;
}
Output
5 30
Related Topics
How to Program for Windows Phone 7 in Standard C++ Only
Conversion from Void* to the Pointer of the Base Class
How to Call a Pointer-To-Member-Function
How to Implement a Map with Different Data Types as Values
Borderless Window with Drop Shadow
Variable or Field Declared Void
Erasing Vector::End from Vector
Specialization of 'Template<Class _Tp> Struct Std::Less' in Different Namespace
Free Function Versus Member Function
Why Implicit Conversion Is Harmful in C++
C++ Static_Cast Runtime Overhead
C++ Expression Must Have a Constant Value
Passing Constexpr Objects Around
What Happens When I Assign a Number Larger Than Int_Max to an Int
Const Variable Changed with Pointer in C