I am learning C and some things confuse me and the books I have read didn't really help in clarifying the problem I have.
So here is the code I have:
#include <stdio.h>
#include <stdlib.h>
#define ARRAY_SIZE 5
// gcc -std=c99 stackoverflow-example.c
int main () {
// declare variable array1
int array1[ARRAY_SIZE];
// declare and init variable array2
int array2[ARRAY_SIZE] = {}; // for integers, the default value is 0
// not initialized
for (int i = 0; i < ARRAY_SIZE; i++) {
// can be anything, not guaranteed to be 0
printf("array1[%d]: %d\n", i, array1[i]);
}
// initialized with initialization list
for (int i = 0; i < ARRAY_SIZE; i++) {
// element == 0
printf("array2[%d]: %d\n", i, array2[i]);
}
// This is the part that confuses me.
// array1 = {}; // error: expected expression before ‘{’ token
// array1[] = {}; // same error
return EXIT_SUCCESS;
}
Is there a handy way to initialize this array after its declaration? Or the only way to set every element in array1
is with a for loop, e.g.:
for (int i = 0; i < ARRAY_SIZE; i++)
array1[i] = 0;
// initialized with a for loop
for (int i = 0; i < ARRAY_SIZE; i++)
// now it's guaranteed to be 0
printf("array1[%d]: %d\n", i, array1[i]);
I really appreciate your help. I know it's somewhat of a noob question, but it came up as I was trying to get more comfortable with the C language and tried some non-book-example code.
If you suspect, that there might be something fundamental that I didn't get, please let me know, I'll read up on it.