Below C code is valid or not?
While reading a post, I came across the following code and output of this code according to post is an error saying:
Array eleme开发者_开发百科nt cannot be address of auto variable. It can be address of static or external variables.
#include<stdio.h>
int main()
{
int a=5,b=10,c=15;
int *arr[]={&a,&b,&c};
printf("%d",*arr[1]);
return 0;
}
But when run this code on MinGW and online compiler it works fine without any error.
So would like to know this is perfectly valid or not??
In C99 that's OK, but ANSI is not.
It looks fine to me. I don't see anything wrong with it. If I had to nitpick, it'd be your formatting and indenting... But that's just about it.
EDIT: I think what the post you were referring to meant is that you can't return the address of a local or auto variable. In this example, everything is in the same scope so it's perfectly fine.
EDIT 2: Okay, going back to prior experience, I think I can find "some" weakness in the code. I've seen this on the Intel Compiler.
Since the variable is local, the compiler may promote it to a register. In that case addresses to it are invalid. However, modern compilers need to be able to trace this dependency and avoid putting that variable into a register.
In one case that I encountered a while back, I was accessing the address of the variable via inline assembly - something that the Intel Compiler could not trace. The compiler then promoted the variable to register and my inline assembly kept reading the old value on the stack rather than the register value.
Obviously it was something I shouldn't have done, but it would have been okay if the variable wasn't auto.
I think this error message is a kinda bug of the compiler; it's an unnecessary restriction. Referencing auto (was: local) variables in an array is really dangerous, but in this case, the scope of the array and the referenced variables are the same (tought, it can be "exported" to other scopes, say, calling a function with the array, which grabs some elements of it). There are several ways to make such an error, even ones, which can't detected compile-time. Yes, pointers are dangerous, but life is so.
精彩评论