【发布时间】:2018-05-11 04:57:13
【问题描述】:
所以我有以下 toString 函数:
/*
* Function: toString
* Description: traduces transaction to a readable format
* Returns: string representing transaction
*/
char* toString(Transaction* transaction){
char transactStr[70];
char id[10];
itoa(transaction -> idTransaction,id, 10);
strcat(transactStr, id);
strcat(transactStr, "\t");
char date[15];
strftime(date,14,"%d/%m/%Y %H:%M:%S",transaction -> date);
strcat(transactStr, date);
strcat(transactStr, "\t");
char amount[10];
sprintf(amount,"%g",transaction -> amount);
strcat(transactStr,"$ ");
strcat(transactStr, amount);
return transactStr;
}
CLion 用警告高亮返回行:Value escapes local scope(指transactStr)
我需要知道为什么会这样(我是 C 新手,顺便说一句)
【问题讨论】:
-
您正在返回一个(指向)local 变量的(指针)。这可能会导致(并且可能会导致)未定义的行为,因为一旦函数结束,该值将“消失”。要么使用 malloc() 分配缓冲区,要么更改函数以接受缓冲区并填充它。您也没有将缓冲区初始化为至少一个 0。
-
你没有初始化transactStr,所以你的第一个strcat()应该是strcpy()。