I made this code and tested it:
int main(void) {
int vetor[10] = {0};
vetor[10] = {0}; //há um erro aqui mas compila em C++
return 0;
}
Compiling in C doesn’t really work because C doesn’t have extended initiators. The syntax of C allows this syntax to be used in the declaration but cannot be used in later assignment, so it explains why the first one you quoted gives problem and the second example your works. See on ideone.
Already if you do the same thing using a modern C++ , at least C++11, this feature is available and can be used. See on ideone. Note that the error message shows that you should use at least C++11.
Understand that C and C++ are different languages. And even language version difference can change the result. You cannot use what is not in the default, not invented yet, or not implemented in the compiler you are using. In C there is no solution but to initialize the elements in the traditional way. In C++ just choose to compile with the newest version available in GCC.
The actual solution only allows zero the array on startup. Then you can allocate numbers on all elements through a loop. In this case it doesn’t necessarily have to be a zero. Another option is to call the function memset()
which also only allows zero all, after all it was made to work with strings and not numbers (actually the initialization of the whole array is replaced internally by a memset()
). See correct examples:
#include <stdio.h>
#include <string.h>
int main(void) {
int vetor[10] = {0};
for (int i = 0; i < 10; i++) printf("%d", vetor[i]);
for (int i = 0; i < 10; i++) vetor[i] = 1;
for (int i = 0; i < 10; i++) printf("%d", vetor[i]);
memset(vetor, 0, sizeof(vetor));
for (int i = 0; i < 10; i++) printf("%d", vetor[i]);
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
I’ll be better if I have more details.
Put your code in for us to see. Only with this you can not understand well where the problem is.
– Maniero
Note that an array defined with
int vetor[10]
does not have the elementvetor[10]
... the elements of this array go fromvetor[0]
tovetor[9]
.– pmg