Janusz01
Janusz01

Reputation: 517

array initialisation with 0 in c

I made an int array in C and initialised it with 0 as follows -

int f[10000] = {0};

My program demanded me to reinitialise this array in the end of the loop. So, I performed this step -

f[10000] = 0;

But this didn't worked. I even tried

f[10000] = {0};

but got error in it too. Ultimately, I had to use memset. Can anyone help as in where is the error occurring and why?

EXTRA INFO - I USED ideone.com FOR CODING PURPOSE

For the reference, here is the complete code -

#include <stdio.h>

int main(void) {
    int t, n, k, f[10000] = {0}, c[10000] = {0}, i, v, count = 0;
    scanf("%d", &t);
    while (t--) {
        scanf("%d %d", &n, &k);
        for (i = 1; i <= n; i++) {
            scanf("%d", &v);
            if (v == i) {
                f[i] = 1;
            }
            c[v]++;
        }
        for (i = 1; i <= n; i++) {
            if (!f[i] && c[i] >= k) {
                count++;
            }
        }
        printf("%d\n", count);
        count = 0;
        memset(f, 0, 10000);
        memset(c, 0, 10000);
        //f[10000] = 0; this didn't worked
        //c[10000] = 0; this didn't worked
    }
    return 0;
}

Upvotes: 2

Views: 99

Answers (3)

jxh
jxh

Reputation: 70382

As previously mentioned, you cannot assign to an array. However, you can assign to a struct.

struct foo { int f[1000]; } f = {};

Then,

f = (struct foo){};

Upvotes: 0

AndersK
AndersK

Reputation: 36082

If you did like this

int f[10000] = {0};

then

f[10000] = 0;

is wrong since index starts at 0 in C so you are writing outside the array bounds.

Upvotes: 1

unwind
unwind

Reputation: 399753

In C, initialization is not the same as assignment, although both use =.

int foo[3] = { 0 };

means "make foo an array of three integers, all initialized to zero", but foo[3] = 0; means "set the fourth element of foo to zero". Clearly different.

And since memset() works in bytes, this:

memset(f, 0, 10000);

is wrong, it should be:

memset(f, 0, sizeof f);

as long as f is a proper array as in your code.

Also beware that very large arrays as automatic variables might not be very portable.

Upvotes: 7

Related Questions