Is there any way by which I can initialize all the elements of an array(already declared) in one statement?? That is, without using loops

You can't initialise anything that has already been declared. You can only initialise something at the time it is created, after that it becomes assignment.

And to answer the spirit of your question no there is no way to assign to all members of an existing array without recourse to a for loop (with the exception of using memset on an array of char).

hey there,
And if you want to ask is if we can initialize at the time of declaration we do it like this,

int a[10]={1,2,3,4,5};

To assign a value later to any element of the array code will be,

a[1]=33;
a[4]=55;

Anirudh

Edited 5 Years Ago by anirudh33: n/a

If you want to initialize all the elements of an array to 0, you can use this

#define SIZE 5
int my_array[SIZE] = {0};

Check out memset and memcpy also.

You can't initialise anything that has already been declared. You can only initialise something at the time it is created, after that it becomes assignment.

Not true. By setting a value, (for example- a loop counter before a while loop) is initializing the value.

Edited 5 Years Ago by WaltP: n/a

Not true. By setting a value, (for example- a loop counter before a while loop) is initializing the value.

When you do that, aren't you declaring that variable?? That makes the guy you quoted correct.

I guess the terminology has changed, then. For the past 35 years initializing a variable has been setting it to a know value just before entering a piece of code (like a loop) that does some kind of processing. When did that change?

What you call initializing I always called defining.

Edited 5 Years Ago by WaltP: n/a

I've been learning just about 1-2 years now, but initializing has always been basically assigning a value when the variable, or whatever it is, is being declared.

I've don't know how you put a counter before a while loop. I know about IN the for loop though, so I guess we are WAY different

I think The initializer for an array is a comma-separated list of constant expressions enclosed in braces ({ }). The initializer is preceded by an equal sign (=). You do not need to initialize all elements in an array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type.


for eg:
Element Value Element Value
matrix[0][0] 1 matrix[1][2] 0
matrix[0][1] 2 matrix[1][3] 0
matrix[0][2] 0 matrix[2][0] 5
matrix[0][3] 0 matrix[2][1] 6
matrix[1][0] 3 matrix[2][2] 0
matrix[1][1] 4 matrix[2][3] 0


-------------------------------------------
<URL SNIPPED>

Edited 5 Years Ago by peter_budo: Keep It Spam-Free - Do not sign your posts with 'fake signatures'

Comments
spammer
This article has been dead for over six months. Start a new discussion instead.