The file1.c defines an array 'myarray' as,
int myarray[10];
The file2.c uses 'myarray' as,
extern int *myarray;
void foo()
{
myarray[0] = 10;
}
What kind of problem this program may have?
Thanks !
Printable View
The file1.c defines an array 'myarray' as,
int myarray[10];
The file2.c uses 'myarray' as,
extern int *myarray;
void foo()
{
myarray[0] = 10;
}
What kind of problem this program may have?
Thanks !
it'll work as long as you don't do something stupid. such as accessing elements out of the actual defined bounds. In that case "anything could happen".
if you defined it extern properly, the compiler could potentially spot an out of bounds access with a warning (assuming the index is calculable at compile time)
"accessing elements out of the actual defined bounds" would be a problem in general everywhere.
When you say, "if you defined it extern properly" what do you mean here ?
Plenty. It's generally considered bad programming practice to have global data (state).
http://c2.com/cgi/wiki?GlobalVariablesAreBad
What isin that line of code? It is sizeof(int) * 10, which is probably 40 bytes (assuming int's are 4 bytes). Then this:Code:sizeof(myarray)
What isQuote:
The file2.c uses 'myarray' as,
extern int *myarray;
in that code? it is sizeof(int*), which is probably 4 or 8 bytes. See the problem? So which one is right? You have two different values for sizeof(). If you now access myarray believing it can hold 10 ints, what if it can't hold 10 ints, but instead is only 4 (or 8) bytes in size? You now have a memory overwrite.Code:sizeof(myarray)
If you are to use extern, the proper way to use extern is to make sure you use the same type. An array is not a pointer:
is to be matched with:Code:int myarray[10];
Regards,Code:extern int myarray[10];
Paul McKenzie
Thanks a lot !