The first problem that causes the code to not work is not allocating space for the terminator in the string that passes to itoa
. Remember that the result is a correctly terminated string as soon as you have at least two characters, what you put in and the terminator.
So char a[1]
must be at least char a[2]
. The itoa
itself is something that you should not use since it is not standard and therefore not available in all compilers, like mine. You should instead use sprintf
which is easy in it and is standard .
The other problem is that each concatenation is permanent over the string ent
. That's why your texts are growing: E00
, E001
, E0012
, etc. Each iteration of for
must start in the original string, which can be done by duplicating the original with strdup
before using.
Correcting these two problems and keeping itoa
would look like this:
int main() {
char ent[3] = {'E','0'};
char a[2];
int n=5;//exemplo
for (int i = 0; i < n; i++) {
itoa(i,a,10);
char *ent_dup = strdup(ent); //criar duplicado
strcat(ent_dup,a); //usar duplicado até ao fim
printf("novo ent: %s \n ",ent_dup);
free(ent_dup); //liberar duplicado
}
return 0;
}
Note that you have to release the string returned by strdup
through free
if you want to avoid memory leaks.
Using sprintf
would look like this:
int main() {
char ent[3] = {'E','0'};
char saida[10];
int n=5;
for (int i = 0; i < n; i++) {
sprintf(saida, "%s%01d", ent, i);
printf("novo ent: %s \n ",saida);
}
return 0;
}
View this latest version on Ideone