[NTLUG:Discuss] Re: OT C question

Todd Robinson techvista at verizon.net
Mon Feb 20 14:24:28 CST 2006


> I just recently ran into this funny situation and I don't understand the 
> fix very well.  Here is the example I was working with:
>
> extern unsigned char *myarray;
>
> void myfunc(unsigned char *somearray);
>
> void main(void)
> {
> 	myfunc(&myarray);
> 	myarray[0] = '*';
> 	*(myarray+1) = '*';
> }
>
> 1> The function call only worked when the & was added in front of 
> myarray.  This doesn't make any kind of sense to me 
Have you confirmed that myarray is initialized correctly? Is it pointing 
to a char array or some random address?

myfunc(&myarray) results in giving myfunc() the address of a pointer to 
a char (char **). In fact, some compilers would complain about that. 
What issues did you have with passing without '&'? Perhaps myfunc() 
derefs somearray twice ( ie: *somearray[3] ). Maybe I'm reading into the 
example too much but the code almost suggests that myfunc() is providing 
the char array to be used by the subsequent statements. In that case, 
calling it with the address of the char * variable makes sense (despite 
myfunc's parm not being defined as char **somearray). If myfunc() is 
supplying the char array, obviously safeguards need to be in place to 
make sure it was successful before using myarray later.

The other two statements in main() look perfectly legal (as long as 
myarray is pointing to a char array of at least 2 bytes). What symptom 
did you see when using the bracket notation? My guess is it's some quirk 
with the rare compiler you are using.

Using the ... char myarray[] for defining an array of char is a better 
coding practice (IMO) but the compiler should allow both approaches. 
Perhaps the compile rules could be made less restrictive (assuming you 
"must" code the way you showed).





More information about the Discuss mailing list