I met a question about the behaviour of returning local pointers in C. I have a code:
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;
}
The pointer name
and name2
both point to a local array. And both of them are local pointers. However, name2
can be successfully returned. I am so confused. Could anyone give me an explanation?