is this what you are after?
char* list[] = {"A", "B", "C"};
int counter[] = {1, 1, 1};
Just declare them both globally and initialize counter
just like you initialize list
.
It is also possible to declare counter
globally and then initialize it in main()
or wherever with a for
loop:
char* list[] = {"A", "B", "C"};
int counter[3];
int main(void) {
for (int i = 0; i < sizeof(list) / sizeof(*list); i++) {
counter[i] = 1;
}
}
or even better, figure out how much memory you need for counter
based on the size of list
:
char* list[] = {"A", "B", "C"};
int *counter;
int main(void) {
int numElements = sizeof(list) / sizeof(*list);
counter = malloc(numElements * sizeof(*counter));
// check for malloc() failure
for (int i = 0; i < numElements; i++) {
counter[i] = 1;
}
}
Notice that you can't simply use sizeof(list)
...that will return how much memory list
has allocated. You need to divide sizeof(list)
by the size of each element, sizeof(*list)
, to get the number of elements