That pointer there is not with memory allocated to it... My suggestion is to create a temporary variable of a slightly larger size and then allocate space based on the final size of this string, remembering to allocate 1 more space to the ' 0'.
char* des_showDesconto(Desconto* d){
char* saida;
char temp[500]; // tou usando 500 para o tamanho maximo da string, imaginando que nunca vá existir algo que chegue a esse valor.
sprintf(temp, "%.2f%% / %d item(ns)", des_getValor(d), des_getQntd(d));
saida = (char*) malloc(sizeof(char) * (strlen(temp) + 1));
strcpy(saida, temp);
return saida;
}
The same reasoning serves another function...
Try to organize better in the next questions so that people can execute your code... the way it is there does not compile: these functions getValor and getQntd for example, the definition is not in the code but as the name was suggestive enough, I managed to generate a code that runs. I’ll stick it down:
typedef struct Desconto{
int qntd;
float valorDesconto;
} Desconto;
typedef struct item{
int ID;
int qntd;
float valor;
char* descricao;
Desconto* desconto;
} item;
char* des_showDesconto(Desconto* d){
char* saida;
char temp[500]; // tou usando 500 para o tamanho maximo da string, imaginando que nunca vá existir algo que chegue a esse valor.
sprintf(temp, "%.2f%% / %d item(ns)", d->valorDesconto, d->qntd);
saida = (char*) malloc(sizeof(char) * (strlen(temp) + 1));
strcpy(saida, temp);
return saida;
}
char* itm_showItem(item* i){
char* saida;
char temp[500];
sprintf(temp, "ID: %d\nQuantidade: %d\nValor: %.2f\nDescricao: %s\nDesconto: %s\n",
i->ID,
i->qntd,
i->valor,
i->descricao,
des_showDesconto(i->desconto));
saida = (char*) malloc(sizeof(char) * (strlen(temp) + 1));
strcpy(saida, temp);
return saida;
}
int main()
{
item i1;
Desconto d;
i1.ID = 10; i1.qntd = 2;
i1.valor = 4.5;
i1.descricao = (char*) malloc (sizeof(char) * 10);
strcpy(i1.descricao, "aew papai");
i1.desconto = &d;
d.qntd = 1;
d.valorDesconto = 0.05;
printf("%s\n", itm_showItem(&i1));
}
Remember that these strings that are being returned from the functions are being allocated in the heap, it is nice to give them a free.
If I declare your var
saida
asstatic char saida[TAM_FIXO]
and make the return asreturn &saida
, not right?– Shinforinpola
If you think your var
saida
There’s nothing, just pointing nowhere. I think it’s worth taking a look at this string question at c: https://answall.com/questions/321313/doubt-sobre-char-em-c– Shinforinpola