How to Initialize All Elements in an Array to the Same Number in C++

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

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

Initialization of all elements of an array to one default value in C++?

Using the syntax that you used,

int array[100] = {-1};

says "set the first element to -1 and the rest to 0" since all omitted elements are set to 0.

In C++, to set them all to -1, you can use something like std::fill_n (from <algorithm>):

std::fill_n(array, 100, -1);

In portable C, you have to roll your own loop. There are compiler-extensions or you can depend on implementation-defined behavior as a shortcut if that's acceptable.

Initialize all the elements of an array to the same number

He assumes that long is four times longer than short (that is not guaranteed; he should use int16_t and int64_t).

He takes that longer memory space (64 bits) and fills it with four short (16 bits) values. He is setting up the values by shifting bits by 16 spaces.

Then he wants to treat an array of shorts as an array of longs, so he can set up 100 16-bit values by doing only 25 loop iteration instead of 100.

That's the way your teacher thinks, but as others said this cast is undefined behavior.

Initializing an array in c with same numbers leads to different values

In your program, you are initializing the array n -

int n[ 10 ] = {002535};

The number 002535 is interpreted as a octal number because of leading zeros.
So, this will assign the octal value 002535 to n[0] i.e. 0th location in your array n and rest of array elements will be initialized with 0.

In for loop, you are printing it with format specifier %d.

The decimal equivalent of 002535 octal value is 1373. That's why you are getting Element [0] as 1373.

If you want to print octal number as output, use %o format specifier:

for (j = 0; j < 10; j++ ) {
printf("Element[%d] = %o\n", j, n[j] );

And if you want the decimal 2535 as first element of array n, remove leading zeros:

int n[ 10 ] = {2535};

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.

How to initialize an array with only -1 values

If you are using gcc then use designated initializer

int array[90] = { [ 0 ... 89 ] = -1}

int array[90],i;
for(i = 0; i < 90 ; arr[i++] = -1);

To do this dynamically , you will have to allocate using malloc then you only free the memory, otherwise freeing the memory which is not allocated by malloc , calloc or realloc is undefined behavior.

Use this:

int *array;
array=malloc(sizeof(int)*n);
for(i=0;i<n;array[i++]=-1);
// After use free this
free(array);

Initializing entire 2D array with one value

You get this behavior, because int array [ROW][COLUMN] = {1}; does not mean "set all items to one". Let me try to explain how this works step by step.

The explicit, overly clear way of initializing your array would be like this:

#define ROW 2
#define COLUMN 2

int array [ROW][COLUMN] =
{
{0, 0},
{0, 0}
};

However, C allows you to leave out some of the items in an array (or struct/union). You could for example write:

int array [ROW][COLUMN] =
{
{1, 2}
};

This means, initialize the first elements to 1 and 2, and the rest of the elements "as if they had static storage duration". There is a rule in C saying that all objects of static storage duration, that are not explicitly initialized by the programmer, must be set to zero.

So in the above example, the first row gets set to 1,2 and the next to 0,0 since we didn't give them any explicit values.

Next, there is a rule in C allowing lax brace style. The first example could as well be written as

int array [ROW][COLUMN] = {0, 0, 0, 0};

although of course this is poor style, it is harder to read and understand. But this rule is convenient, because it allows us to write

int array [ROW][COLUMN] = {0};

which means: "initialize the very first column in the first row to 0, and all other items as if they had static storage duration, ie set them to zero."

therefore, if you attempt

int array [ROW][COLUMN] = {1};

it means "initialize the very first column in the first row to 1 and set all other items to zero".



Related Topics



Leave a reply



Submit