Link to home
Start Free TrialLog in
Avatar of simbo
simbo

asked on

Explanation on compiler error needed.

I consider myself a mediocre C/C++ programmer but I just saw a line of code that stumped me. Anyone who can provide an answer is greatly appreciate.

This is the code

unsigned char DataBuffer[80];
unsigned char *BufferPtr;

.....

BufferPtr = (DataBuffer + 4) & (~0x3);

.....

This is the error "error C2296: '&' : illegal, left operand has type 'unsigned char *'"

Why is this kind of pointer manipulation not allowed?


Avatar of grg99
grg99

What they're trying to do is to align BufferPtr to the next multiple of 4 address.  

The problem might be that on your computer the constant ~3 might not be the same width as a pointer.
You could probably fix this by casting everything to to a unsigned char *:

typedef  unsigned char * ucp;

    BuferPtr = (ucp) (    (ucp)(  DataPtr+3 )   &   ( (ucp)(~3) )    )

A couple other points:

Once the pointer is aligned, we've lost anywhere from zero to three bytes of the array size.
So anything you later do with that array had better not use more than 77 bytes!


Avatar of simbo

ASKER

Thanks for the response grg99. I've tried that already before posting the question and the compiler responded with the same error message.

The error message I got was

"error C2296: '&' : illegal, left operand has type 'unsigned char *'
error C2297: '&' : illegal, right operand has type 'unsigned char *'"

I've used both ARM compiler and visual C++ and both compilers gave me the same kind of error. "..... '&':illegal left operand ........"

Any other ideas? Thanks
ASKER CERTIFIED SOLUTION
Avatar of efn
efn

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Narendra Kumar S S
Try out the following.....it will work!
BufferPtr = (unsigned char *) ( ((int)dataBuffer + 4) & (~0x3) );

The problem was due to the array name in the operator list for bitwise (&) operator. Array name will be converted to an address and this cannot be given as an operator for bitwise-operators.....it always expects an int type of operator. So, convert this to int by typecasting to int.
But, the result has to be given to a pointer and this pointer is of type unsigned char. So, you have to typecast it to the pointer of that type and while doing this, the entire expression must be placed within the braces!
Hope you understood why it was giving error before...!?
Avatar of simbo

ASKER

Thank you everyone for their help. I accepted the answer from efn because his is  the most complete and was posted the earliest