Jon S
Jon S

Reputation: 69

How to set all the elements of array to 0, after initialization or 2nd time in a loop?

I am stuck with basics of an array. I googled it, but I could not able to solve this. This question is concept oriented, but I am not able to bridge a gap. Please help me out resolve this.

I am very clear on initializing array for the first time, but not able to clear the array for next time :-( :-(

int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }; // All elements of myArray are 5
int myArray[10] = { 0 };    // Will initialize all elements to 0
int myArray[10] = { 5 };    // Will initialize myArray[0] to 5 and other elements to 0
static int myArray[10]; // Will initialize all elements to 0

int myArray[10];// This will declare and define (allocate memory) but won’t initialize
int i;  // Loop variable
for (i = 0; i < 10; ++i) // Using for loop we are initializing
{
    myArray[i] = 5;
}

Problem statement:

I am using a Global array which is of size 10000. I have 1k iteration loop, where I have to set the array to 'Zero' or predefined value i.e., 5 for each iteration.

I am doing this at the end of interaction like this:

myArray[10000] = { 0 };

Its giving error while compiling in GCC compiler.

error: [11707] syntax error before '{' token

Please help me out resolve this.

Thanks in advance.

Upvotes: 2

Views: 25963

Answers (2)

ddz
ddz

Reputation: 526

The trivial implementation of memset, without any optimization, is a loop that set each position of an array to a desired value. The problem is memset do this for each byte, and it is not what you want. I recommend you to implement an alternative to memset:

int *mymemset (int *s, int v, size_t n) {
    unsigned int *p = s;
    while(n--) {
        *p++ = (unsigned int)v;
    }

    return s;
}

And use it to initialize your array.

Upvotes: 0

totoro
totoro

Reputation: 2456

myArray[10000] = { 0 };

is an assignment, not a declaration, so it won't work. You should loop.

int myArray[10000] = { 0 };

for(int i = 0; i < 1000; i++) {
    for (int j = 0; j < 10000; j++) {
        myArray[j] = ;  // put your value here.
    }
}

I am unsure of the purpose of this. Benchmarking?

Upvotes: 4

Related Questions