I have a struct defined as following:
struct Complex {
double _real;
double _img;
};
I am trying to create a function that returns a pointer to a new complex number based on a c-string input. I begin doing so by trying to create a struct, based on what I've seen on other stackoverflow questions:
struct Complex * newComplex = (struct Complex*)malloc(sizeof(struct Complex));
Sadly, the code crushes at runtime, saying:
0 [main] complex 14380 cyg
trace to complex.exe.stackdump
I also tried running the following, resulting with the same error:
struct Complex * newComplex;
newComplex = (struct Complex*) malloc(sizeof(struct Complex));
When I tried debugging this piece of code, I broke it to parts, coming up with the following code, which seems to work properly:
struct Complex * newComplex = (struct Complex*)malloc(sizeof(struct Complex));
void *temp = malloc(sizeof(struct Complex));
newComplex = (struct Complex*) temp;
I would love to have an explanation to this behaviour.