简体   繁体   中英

Function returning pointer to array - cast and get value

I have little dilemma with my code.

I have function which returns pointer (uint8_t*) to data buffer. Is it possible and legal to cast this pointer to uint16_t when I need 2 values from array as uint16_t? Or there will be problem with aligning? Buffer is filled via byte reading from I2C.

The problem exists on MCU but when I try this with visualstudio, it´s ok. MCU - Hardfault

uint8_t arr[8];

uint8_t * FuncReturnPointer(void)
{
     arr[0] = 0xEE;
     arr[1] = 0xFF;

     return arr;
}

main
{
     uint16_t val16 = 0;

     val16 = *(uint16_t*)FuncReturnPointer();
}

Is there something wrong/dangerous?

There are two separate issues here:

  • strict aliasing violation
  • possible alignment violation

Either of these can lead to various "interesting" phenomena. I could bet that this is due to alignment violation, ie arr does not happen to reside at an address divisible by _Alignof(uint16_t) . The proper fix is to use either

  • arithmetic:

     val16 = ((uint16_t)*address << 8) | (address);
  • memcpy :

     memcpy(&val16, address, sizeof (val16));

uint8_t, uint16_t, char etc. types in pointers actually tells the program to how to treat the value in the pointed address. Your function "FuncReturnPointer" returns the address of the "arr" array which is a 8-bit type array. When you add (uint16_t *) type converter into that function what it does actaully is treat it as a 16-bit number and store it as 0x00EE not 0xEE. Good practice would be something like this:

main
{
     uint16_t val16 = 0; 
     uint8_t *address;

     address = FuncReturnPointer();  //this gets the address of the arr
     val16 = (*(address++)<<8) + (*address);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM