[NTLUG:Discuss] OT C question

Johnny Cybermyth djcybermyth at sbcglobal.net
Mon Feb 20 09:57:09 CST 2006



Greg Edwards wrote:
> 
> Not a problem.  Pointer sizing is a preprocessor issue same as constant 
> type casting.  The compiler will take care of the type casting and 
> sizing of structure (or type) pointer and increment the physical pointer 
> that many bytes.  A ++ptr is the same thing as ptr=(ptr+1) or 
> ptr=&ptr[1]. Thats why pointer arithmetic is portable between 
> architectures.
> 

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 since the name 
myarray should be the address of the first element of the array, which 
is what myfunc is expecting.

2> accessing myarray using the bracket notation just didn't work but the 
parenthesis method did.

I ran into this problem while using the Microchip c18 PIC compiler and 
then checked this using MinGW.  They behaved the same way.  If I change 
my array declaration to:

extern unsigned char myarray[];

then everything behaved as expected.  So, what I took away from this 
little exercise is that if you declare an array using the char * method, 
you have to use only that method when accessing the array, and the same 
holds true for the [] method.  As for the function call, I don't 
understand that at all.

Any thoughts?




More information about the Discuss mailing list