[NTLUG:Discuss] OT C question
Johnny Cybermyth
djcybermyth at sbcglobal.net
Mon Feb 20 15:38:26 CST 2006
It would compile, but as you stepped through the code, the array wasn't
updated by either the function call or the assignment statement. I'll
post the actual code so our home audience can follow along!
I was using 2 files for my test since I originally thought it was a
module linking problem. Here are the original files:
// main.c------------------------------------
extern unsigned char myarray[];
extern void myfunc(unsigned char *somearray);
void main(void)
{
myfunc(myarray);
myarray[0] = '*';
myarray[1] = '*';
}
// file1.c------------------------------------
unsigned char myarray[5];
void myfunc(unsigned char *somearray)
{
*somearray = ~(*somearray);
*(somearray + 1) = ~(*(somearray + 1));
}
// end files ---------------------------------
These files work perfectly as written. If you modify the the extern
statement in main.c to:
extern unsigned char *myarray;
the array won't update correctly. Also, if you try to change the code
inside of file1.c to use brackets, you won't update the array.
I totally agree with you. I couldn't believe what I was finding with
this code. I'll be the first to admit that I've probably introduced
some logical error or something, but this is what I've found to be true
in practice. I'm using the Microchip c18 compiler, so I decided to
inspect the generated assembly code and noticed that the two methods
described above with referring to the external array actually generated
different assembly code when accessing the array. I thought that maybe
the compiler was funny, but I tested the same files using MinGW and got
the same results, debugging with gdb. Admittedly, I am not very
comfortable using gcc and had to learn gdb just for this test, so I may
have done something wrong in the sanity test.
Let me know if you find differently. Thanks for looking at this!
--Johnny
Patrick R. Michaud wrote:
>
>
> Standard C and C++ have always held that
>
> array[n]
> *(array+n)
>
> are equivalent, so it shouldn't have made any difference. So
> there must be something else going on here.
>
> Pm
More information about the Discuss
mailing list