返回本地指针

时间:2019-10-28 07:01:03

标签: c memory-management

我遇到了一个有关在C中返回局部指针的行为的问题。 我有一个代码:

static void *uar(int c)
{

    char name[3]={"OK"};
    char *name2;
    name2 = name;
    if(c == 0)
        return name;
    else
    return name2;
}

int main(){
    char *res;
    char *res2;
    res = uar(0);
    res2 = uar(1);
    printf("The res is %s\n",res);
    printf("The res2 is %s\n",res2);
    return 0;
}

指针namename2都指向本地数组。而且它们都是本地指针。但是,name2可以成功返回。我感到很困惑。谁能给我一个解释?

0 个答案:

没有答案