C : Value escapes local scope?

假装没事ソ 提交于 2019-12-09 05:25:50

问题


So I have the following toString function:

/*
 * 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 highlights the return line with a warning: Value escapes local scope (referring to transactStr)

I need to know why this is happening (I'm new to C, btw)


回答1:


You've defined a local variable pointer (edit thanks) inside that function and are trying to return it.

That's a no-no, as the variable's lifetime is only that of it's enclosing scope, here, the function call. Anyone trying to reference the return value will trigger undefined behavior, usually a crash, if you're lucky.

If you want to return the array, you need to pass it in as an argument.



来源:https://stackoverflow.com/questions/44222061/c-value-escapes-local-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!