The first problem that causes the code to fail is that it is not allocating space to the terminator in the string that passes to itoa
. Remember that the result is a correctly completed string so it will have at least two characters, what you have put and the terminator.
That’s why char a[1]
it has to be at least char a[2]
. The very one itoa
is not something you should use because it is not standard and so it is not available on all compilers, as in mine. You should instead use sprintf
that is easy in the same 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. With each iteration of the for
has to start in the original string, which can duplicate the original with strdup
before using.
Fixing these two problems and keeping the 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;
}
See this latest version on Ideone
I think with your use of
sprintf
is unnecessary to concatenate withstrcat
– Jefferson Quesado
@Jeffersonquesado Yes it is indeed. I just switched the
sprintf
foritoa
and I didn’t even remember I could do everything with just thesprintf
. Thank you for the comment.– Isac
for nothing. I put a supplementary answer that made more sense before its edition. I think now it would be better to merge my answer in yours, which you think?
– Jefferson Quesado
@I don’t think so. Looks good just as it is as a complement, and with a variant of using ascii straight to when number has only one digit.
– Isac