Click here to Skip to main content
14,695,085 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to initialize an array and assigning a value i.e. 20 for all elements in one statement.
To initialize all elements to zero we write. int a[] = {};
[no name] 2-May-14 16:39pm
int a[5] = {20,20,20,20,20};
khaledkee 2-May-14 17:32pm
what if the array of size 1000. i can't write 1000 "20"s
[no name] 2-May-14 22:51pm
What if? You asked and got your answer. You said nothing about the size of the array.
Maciej Los 2-May-14 17:34pm
Sounds like answer ;)

1 solution

You probably have to call the memset function. However, have a look at this Stack Overflow question[^].
khaledkee 2-May-14 17:33pm
Does memset perform loops or takes unreasonable time with large size of the array.
In CPU instruction set, writing to a big continuous memory area is anyway based on a loop, so C can generate perfectly optimal code for that, which cannot be faster.
khaledkee 2-May-14 18:29pm
Thanks for explanation.
You are welcome. Good luck learning programming.
Maciej Los 2-May-14 17:35pm
CPallini 3-May-14 4:28am
Thank you.
CPallini 3-May-14 4:28am
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900