-2

我有如下所示的 C++ 代码:

static int* ArrayGenerator()
{
    int temp[1] = {9};
    return temp;
}

static int* ArrayGenerator(int i)
{
    //parameter is just for demonstration
    int temp[1] = {9};
    return temp;
}

int _tmain(int argc, _TCHAR* argv[])
{
    int arr1[1] = {9};
    printf("arrays are %s equal\n\n", (memcmp(arr1, ArrayGenerator(), 1) == 0) ? "" : "not");
    printf("arrays are %s equal\n\n", (memcmp(arr1, ArrayGenerator(1), 1) == 0) ? "" : "not");
}

第一个给我“平等”,第二个给我“不平等”。

为什么是这样?

4

1 回答 1

0

您不能从函数返回本地指针。当您从函数返回 temp 时,它超出范围并且内存不再有效。这会导致未定义的行为。我已经在这里解释过了

于 2014-01-07T17:19:36.573 回答