Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set all elements of an array to zero or any same value? [duplicate]

Tags:

arrays

c

linux

I'm beginner in C and I really need an efficient method to set all elements of an array equal zero or any same value. My array is too long, so I don't want to do it with for loop.

like image 308
user3610709 Avatar asked May 07 '14 05:05

user3610709


People also ask

How do you make all elements of an array equal 0?

If your array has static storage allocation, it is default initialized to zero. However, if the array has automatic storage allocation, then you can simply initialize all its elements to zero using an array initializer list which contains a zero.

How do you assign the same value to all elements in an array?

int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index. The array will be initialized to 0 in case we provide empty initializer list or just specify 0 in the initializer list. Designated Initializer: This initializer is used when we want to initialize a range with the same value.

How do you assign an array to zero?

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 make all elements in an array zero in Python?

You need to make all the elements of the array equal to 0 by performing the below operations: If an element is 1, You can change it's value equal to 0 then, if the next consecutive element is 1, it will automatically get converted to 0.


2 Answers

If your array has static storage allocation, it is default initialized to zero. However, if the array has automatic storage allocation, then you can simply initialize all its elements to zero using an array initializer list which contains a zero.

// function scope
// this initializes all elements to 0
int arr[4] = {0};
// equivalent to
int arr[4] = {0, 0, 0, 0};

// file scope
int arr[4];
// equivalent to
int arr[4] = {0};

Please note that there is no standard way to initialize the elements of an array to a value other than zero using an initializer list which contains a single element (the value). You must explicitly initialize all elements of the array using the initializer list.

// initialize all elements to 4
int arr[4] = {4, 4, 4, 4};
// equivalent to
int arr[] = {4, 4, 4, 4};
like image 88
ajay Avatar answered Oct 13 '22 00:10

ajay


You could use memset, if you sure about the length.

memset(ptr, 0x00, length)

like image 29
Sawan Avatar answered Oct 12 '22 23:10

Sawan