Can someone explain why this doesn't work?
int main()
{
float* x;
float a, b;
int num_vals = 10;
fill_in_x(&x, num_vals); // malloc is called and x is populated with values
a = x[0];
b = x[1] - x[0];
printf("%f\n", a);
printf("%f\n", b);
function_using_a_and_b(a, b); // The values of a and b used in this function
// don't match those calculated in main
}
void fill_in_x(float** x, int num_vals)
{
*x = (float*)malloc(num_vals * sizeof(float));
// Fill in values for x
}
void function_using_a_and_b(float a, float b)
{
printf("%f\n", a);
printf("%f\n", b);
}
To reiterate what is said in the comments, when I dynamically allocate the memory for x in a malloc in a separate function, then try and pass a couple of the values into another function, the values don't get passed correctly. It feels like a pointing issue, but I thought I was passing the values of a and b, not the addresses. For the record, I even tried a memcpy to put the values in a and b, but that didn't do the trick either.
I did get it to work by passing the addresses of a and b and then de-referencing them in function_using_a_and_b, but why doesn't the method above work?
Thanks in advance.