You are trying to strcat() onto a string constant. Even if it didn't cause a segfault, it would make no sense
Printable View
You are trying to strcat() onto a string constant. Even if it didn't cause a segfault, it would make no sense
I can't do:
strcat(descricao[errno]," - Cód.: ");
strcat(descricao[errno],itoa(errno));
That's because I'm trying to modify a literal (descricao), which is not possible.
Right??
Then, I've tried this, but not works too:
Why?Code:char *erro;
erro = descricao[errno];
strcat(erro," - Cód.: ");
strcat(erro,itoa(errno));
return erro;
ok brewbuck
I had not seen your post ... hehe
but why this not work?
Code:char *erro;
erro = descricao[errno];
strcat(erro," - Cód.: ");
strcat(erro,itoa(errno));
return erro;
Because you are trying to extend a string constant, and those are generaly read-only, not to mention that there's unlikely to be "space after" your string. Pass in a string that can be filled in, or have a static local string, or something like that.
--
Mats
How can i do that? Can you post a example?
The line "erro = descricao[errno]" just makes erro point at the same string constant. You need to actually strcpy(erro, descricao[errno]) -- the rest of the code is correct, provided you actually allocate some space for erro. Currently, it's just an uninitialized pointer.
This is the solution:
It works perfectly. Thanks for all.Code:char *abrir_arquivo(char *arquivo)
{
FILE *fp;
char *erro;
char *codstr = " - Cod.: ";
char *desconstr = "Erro desconhecido";
char *abertostr = "Aberto";
if ((fp = fopen(arquivo, "r")) == NULL) {
if ((errno >= 0) && (errno <= 2)) {
erro = malloc(strlen(descricao[errno]) +
strlen(codstr) +
strlen(itoa(errno) + 1));
strcpy(erro, (descricao[errno]));
strcat(erro, codstr);
strcat(erro, itoa(errno));
}
else {
erro = malloc(strlen(desconstr)+1);
strcpy(erro, desconstr);
}
}
else {
erro = malloc(strlen(abertostr) + 1);
strcpy(erro, abertostr);
}
return erro;
}
int main(void)
{
char *message;
message = abrir_arquivo("asdasdasd");
printf("%s\n", message);
free(message);
return EXIT_SUCCESS;
}
:D
I doubt this retuns what you expect...Code:strlen(itoa(errno) + 1)
itoa is not standard
and better check the return value of malloc before using the buffer