简体   繁体   中英

How can I read values of a pointer, being this pointer the return of a function?

This would be my code:

uint8_t* send(uint16_t sw){

uint8_t sw8[2];
uint8_t* data= NULL;

sw8[0]=sw>>8;
sw8[1]=sw&0xFF;

memcpy(data,sw,2);

return data;

}

main(){
uint8_t * resp;

resp = send(x6A00);
}

If sw is 0x6A00 for example, *data will be 6A, and I want it to be 6A00!!!!

uint8_t* data= NULL;
...
memcpy(data,sw,2);

Here, you pass null to memcpy . The behaviour of the program is undefined.

I want [ *data ] to be 6A00!!!!

Then data must point to some array. You can achieve this by initialising the pointer. Exactly how you should do that depends on what you're trying to do.

I want data to point to the sw8. But if I put data=sw8, i will get &sw8[0], i don't access to the whole array, right?

Sure you do. You can simply use data[1] to access the second element.

However, if you do this, then you shouldn't return data because sw8 is an automatic variable within the function, and therefore its lifetime ends and it is automatically destroyed by the end of the function. Therefore returning a pointer to it always returns an invalid pointer.

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