goldshakil / ElectricalProgrammingCourse2020

This repository is aimed towards sharing and discussing issues about Electrical and Electronics Programming Course
6 stars 1 forks source link

[others] lecture assignment 11 #241

Open quilava1234 opened 4 years ago

quilava1234 commented 4 years ago

I have problems with the extra assignment on lecture 11 about the quadratic equation with pointers.

/Assignment calculate the root of quardratic equation ax^2 + bx + c using pointer to have multiple return values roots: x1 x2 real and imag part single function to calculate the roots function should return 4 value x1 R+i x2 R+i /

my code basically works like below:

int *getSol(int a, int b, int c) { double answer[4];

//~calculate the roots and shove them into array answer as elements

return answer;

}

int main{ double *ptr;

//~ get a, b, c input

ptr = getSol(a,b,c); //get answer array's starting address

printf("%f + %f i, %f + %f i", ptr, (ptr+1), (ptr+2), (ptr+3)); //print answers using their addresses

}

I thought by this way I'd get the starting address of the answer array assigned to ptr. Also, by printing the float numbers stored in address ptr, ptr+1, ptr+2, ptr+3 I expected to get my answers I got from my function getSol. But instead, I'm getting weird, big numbers that look like some addresses themselves printed. I wonder if you could help me out on what I'm missing/misunderstood or done wrong.

goldshakil commented 4 years ago

You code has 2 issues: 1) you function's return type should double pointer but your definition is integer pointer.

2) you are returning a local variable(answer array) which is destroyed once the function finishes executing. You have to use static double answer[4].

Please google static in c language for more information.

quilava1234 commented 4 years ago

Oh now I see. Thank you for your help, now my code works just fine.