简体   繁体   English

返回字符数组或指向char literal的指针时的区别

[英]Difference when returning an array of chars or a pointer to char literal

I learned that when I initialize an array of chars it's just like initializing a pointer to chars. 我了解到,当我初始化一个字符数组时,就像初始化一个指向字符的指针一样。 But, if that is the situation, why does the following code output strange characters? 但是,如果是这种情况,为什么以下代码输出奇怪的字符?

char* returnMe()
{
    char text[] = "Will I live forever?";
    return text;
}

While the following code: 而以下代码:

char* returnMe()
{
    char* text = "Will I live forever?";
    return text;
}

outputs: 输出:

Will I live forever? 我会永远活着吗?

What exactly are the differences between these two initializations? 这两个初始化之间到底有什么区别? They both act like pointers, so if I do: 它们都像指针一样,所以如果我这样做:

puts(X); //puts get char* as a parameter in it.

It will work for both cases (When I haven't gone out of scope yet.) 它适用于两种情况(当我还没有超出范围时。)

The function containing this: 包含这个的函数:

 char text[] = "Will I live forever?";

returns a pointer to a local variable called text , which contains the string "Will I live forever?". 返回一个指向名为text的局部变量的指针,该变量包含字符串“我会永远活着吗?”。 As with all local variables, that variable evaporates after the function returns, and so you are off in undefined behaviour land if you try to access it. 与所有局部变量一样,该函数在函数返回后会蒸发,因此如果您尝试访问它,则会在未定义的行为域中关闭。

The function containing this: 包含这个的函数:

 char* text = "Will I live forever?";

returns a pointer to some magic place in memory (but not a local variable) containing the string, which persists for the program's execution, so using that pointer is not undefined behaviour. 返回一个指向内存中某个魔术位置的指针(但不是局部变量),该指针包含该字符串,该字符串会持续执行程序,因此使用该指针不是未定义的行为。

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

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