Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize entire array with a value in C

I was trying to initialise an entire int array and after searching through Stackoverflow, i found that the best way is to use std::fill_n from <algorithm> or <vector> header but including both is giving an error. I think these methods are only possible in C++ or am I doing something wrong?

How can I initialise an entire array with a value in C without any loops i.e. in a single statement?

I am working on Fedora 14 terminal and compiling it using gcc.

like image 793
adimoh Avatar asked Jan 24 '26 04:01

adimoh


1 Answers

If you have your array declaration int arr[ARRAY_SIZE];, then you can fill it with an int VALUE with the following code (the declaration of i needs to be at the beginning of a block).

int i;
for (i = 0; i < ARRAY_SIZE; i++)
   arr[i] = VALUE;

A simple for loop will do.

like image 81
Jashaszun Avatar answered Jan 26 '26 18:01

Jashaszun