Pointer Casting

Status
Not open for further replies.

electroRF

Member
Hi,
I have a question please.

My function receives a char* Pointer for DATA_LOCATION, and needs to pass a unsgined int* Pointer for the same DATA_LOCATION.
i.e.
Input: char *Data8;
Output: unsgined int *Data32;

I'm afraid to do the following conversion, due to alignment problem:
C:
Data32 = (unsigned int *) Data8;

That is a problem since Data8 is aligned to 8-bit addresses, while Data32 should be aligned to 32-bit addresses.

How to overcome such problem?

Thank you
 
What problem??

C:
unsigned int* myfuction(unsigned char* data8)
 {
 stuff;
 return (unsigned int*) stuffresult;
 }

unsigned char* Data8;
unsigned int* Data32;

Data32 = myfunction(Data8);
 
Re edit!!!

I think I missread the problem..


C:
 Data32= ( unsigned int*)  Data8;

Is fine.... This is how to cast!!
 
Hi Ian,
It's a problem, since when you will perform: *Data32
Then,
Some cores expect the Address pointed by Data32 to be 32-bit aligned, because *Data32 Operation fetches 32-bit.
Otherwise, you'll get a Bus Exception.

But the address pointed to by Data8 is only 8-bit aligned.
 
If you have unaligned pointer, then any aligned pointer will not be for the same location. So, it's either same location or aligned pointer. Take your pick.
 
Hi NorthGuy

Thank you.

So you're actually saying that there's no way to work it out - i.e. the function which gets 8-bit aligned pointer, can't (somehow) convert it to 32-bit aligned.
 
Look into unions..... This is the way I align data..... I also use it to serialize...
 
... the function which gets 8-bit aligned pointer, can't (somehow) convert it to 32-bit aligned.

The best it can do is to allocate temporary aligned memory, copy data pointed to by the incoming pointer into there, then pass the pointer to this area to the route which requires aligned pointers. Once the routine is done, it should copy the [possibly] changed data to the space pointed to by the original pointer, then deallocate the temporary memory. To do that, your program must know the size.
 
Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…