Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting an array to one value

Tags:

c

Is there an easier way in C to set an array to one value than using a for loop and going setting each value one by one?

like image 479
Devan Buggay Avatar asked Nov 01 '10 03:11

Devan Buggay


People also ask

How do you assign an array to a single value?

Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.

How do you initialize an array with one value?

Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.

How do you initialize an array with a single value in C++?

Using Initializer List. int arr[] = { 1, 1, 1, 1, 1 }; The array will be initialized to 0 if we provide the empty initializer list or just specify 0 in the initializer list.

How do you initialize an entire array to 1 in Java?

We can declare and initialize arrays in Java by using a new operator with an array initializer. Here's the syntax: Type[] arr = new Type[] { comma separated values }; For example, the following code creates a primitive integer array of size 5 using a new operator and array initializer.


2 Answers

If you're setting the array to all 0's, or if the array is an array of bytes, you can use memset

// Set myArray to all 0's
memset(myArray, 0, numberOfElementsInMyArray * sizeof(myArray[0]));

If you need to set it to something other than 0 in units larger than a byte (e.g. set an array of ints to 1's), then there is no standard function to do that -- you'll have to write your own for loop for that.

like image 153
Adam Rosenfield Avatar answered Sep 21 '22 14:09

Adam Rosenfield


You can set it to the same value, but only to 0

How to initialize all members of an array to the same value?

initialize all elements to 0:

int myArray[10] = { 0 }; // all elements 0

There is an answer in that page for gcc as well.

like image 22
nonopolarity Avatar answered Sep 23 '22 14:09

nonopolarity