Reputation: 49
void func(struct a* para)
{
struct b *alpha;
memcpy(&alpha, para, sizeof(para));
new_func(&alpha); //because this requires struct of type b
}
Am i missing any kind of initializations here? I tried "struct b *alpha {}" also. Is there any other method to copy the structure inside a function? If not advisable, then can someone tell me how to use the memcpy method?
My device throws bus errors and I have observed this error before due to non initialization or some memory related issues.
EDIT:
struct a and struct b are the same
struct a
{
char alpha;
int beta;
}
Upvotes: 2
Views: 186
Reputation: 211610
You're copying data over an uninitialized pointer, and the pointer itself is too small, so it just explodes. An easy fix:
b alpha; // struct prefix not necessary in C++
// Note sizeof(a) not sizeof(a*)
memcpy(&alpha, para, sizeof(a));
// Presuming this takes b* arg, not b** arg as your code implies
new_func(&alpha);
Note that if new_func
retains that pointer it will be invalidated the instant func
exits.
If all this is to just pass in something that's of one type but you want it to be another, just use static_cast
and save yourself all this hassle:
new_func(static_cast<b*>(para));
Upvotes: 3