简体   繁体   English

C:从函数返回指针数组的元素

[英]C: return element of pointer array from function

I'v got question when I practiced section 5.8(page 113) of K & R The C Programming Language. 当我练习K&R The C Programming Language的5.8节(第113页)时,我遇到了疑问。

original source code is here 原始源代码在这里

/* month_name: return name of n-th month */
char *month_name(int n)
{
    static char *name[] = {
        "Illegal month",
        "January", "February", "March",
        "April", "May", "June",
        "July", "August", "September",
        "October", "November", "December"
    };
    return (n < 1 || n > 12) ? name[0] : name[n];
}

And I already know that we can't return local variable's pointer because it's from stack and it will be destroyed(?) after function return. 我已经知道我们不能返回局部变量的指针,因为它来自堆栈,并且在函数返回后将被销毁(?)。 But in this example they use static to remain that variable. 但是在此示例中,它们使用static保留该变量。

The question is "Why they still work after I delete static notation". 问题是“为什么在删除静态符号后它们仍然起作用”。

I changed code to 我将代码更改为

/* month_name: return name of n-th month */
char *month_name(int n)
{
    char *name[] = {
        "Illegal month",
        "January", "February", "March",
        "April", "May", "June",
        "July", "August", "September",
        "October", "November", "December"
    };
    return (n < 1 || n > 12) ? name[0] : name[n];
}

and they still work very well. 而且它们仍然运作良好。

BUT. 但。 if I return name instead of name[n] , it doesn't work as I expected. 如果我返回name而不是name[n] ,那么它将无法正常工作。

Why does it work? 为什么行得通?

It still works because the array contains pointers to string literals. 它仍然有效,因为数组包含指向字符串文字的指针。 String literals have static storage duration even if the array the holds their addresses doesn't. 字符串文字具有静态存储持续时间,即使保存其地址的数组没有。

In fact an optimizing compiler should wise up to the fact, and produce identical code in both cases. 实际上,优化的编译器应该明智地做到这一点,并且在两种情况下都产生相同的代码。

When you return name however, the same rules that you noted apply. 但是,当您返回name时,将遵循您记下的相同规则。 So you get undefined behavior. 这样您就得到了不确定的行为。 Although unless you change the return type of the function, then returning name shouldn't compile, since char* and char** are incompatible types. 尽管除非更改函数的返回类型,否则不应编译返回name ,因为char*char**是不兼容的类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM