1

I wanted to initialize all the elements of my integer array to -2.

I have seen various answers that int A[10] = {0} initializes all 10 elements to 0. But, I couldn't reproduce that with -2.

#include <stdio.h>

int main() {
    int A[10] = {-2};

    printf("%d",A[3]);
}

gives default 0 instead of -2.

How can I do that. The concerned array size is very big.

mr.loop
  • 818
  • 6
  • 20
  • 1
    There's no shortcut. `int A[10] = {-2, -2, -2, -2, -2, -2, -2, -2, -2, -2}` ... or `int A[10]; for (i = 0; i < 10; i++) A[i] = -2;` *You can write a program that outputs `{ -2, -2, -2, ..., -2 }` and use that to initialize your array. Something like* (this is invalid C code though) `int A[1000] = #include ;` – pmg Jun 10 '21 at 13:20
  • Duplicate: [Initializing entire 2D array with one value](https://stackoverflow.com/q/15520880/584518). – Lundin Jun 10 '21 at 13:26
  • 1
    Regarding initializing a big array to certain values at compile-time, see this https://stackoverflow.com/a/13488596/584518 – Lundin Jun 10 '21 at 13:28
  • "How can I do that. The concerned array size is very big." --> implies a better approach to the higher level problem exist. – chux - Reinstate Monica Jun 10 '21 at 13:50
  • @alex01011 I was able to fill it with 0 and -1 by `memset(&A[0], -1, 10*sizeof(int))` but doesn't works for other integers. I am not proficient in memory management yet, so maybe someone can create a general code. – mr.loop Jun 10 '21 at 14:53

1 Answers1

2

Use a loop to assign the desired value to each elements. In typical current computer and compiler with optimization enabled, the cost of memory access should be higher than the cost of looping, so you should only consider the cost of looping only after you actually found it is too slow.

#include <stdio.h>

int main() {
    int A[10];
    for (size_t i = 0; i < sizeof(A) / sizeof(*A); i++) {
        A[i] = -2;
    }

    printf("%d",A[3]);
}
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • Why is it that most answers talk about a way that only works for initializing to 0. Why it doesn't work for other integers – mr.loop Jun 10 '21 at 13:22
  • 1
    Because the specification says that elements whose values are not explicitly specified should be initialized to zero when initializer for some elements are given. – MikeCAT Jun 10 '21 at 13:23