C:价值逃避本地范围? [英] C : Value escapes local scope?

查看:158
本文介绍了C:价值逃避本地范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有以下toString函数:

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突出显示带有警告的返回行:值转义了本地范围(指transactStr)

CLion highlights the return line with a warning: Value escapes local scope (referring to transactStr)

我需要知道为什么会这样(我是C的新手,btw)

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

推荐答案

您已经在该函数内定义了一个局部变量指针(感谢编辑),并试图将其返回。

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.

这篇关于C:价值逃避本地范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆