I am trying to write a function in C to initialize multiple double type arrays, with different sizes. The array size should be given in the function and the array values are assigned through previously defined functions and values. The functions are to be set as void, since I should use them many times later at different places. Here is a version of the code which does not give reasonable results. Thanks for your help!
#include <stdio.h>
#include <stdlib.h>
//interpolation, source code from internet
int findCrossOver(double arr[], int low, int high, double x)
{
// Base cases
if (arr[high] <= x) // x is greater than all
return high;
if (arr[low] > x) // x is smaller than all
return low;
// Find the middle point
int mid = (low + high)/2; /* low + (high - low)/2 */
/* If x is same as middle element, then return mid */
if (arr[mid] <= x && arr[mid+1] > x)
return mid;
/* If x is greater than arr[mid], then either arr[mid + 1]
is ceiling of x or ceiling lies in arr[mid+1...high] */
if(arr[mid] < x)
return findCrossOver(arr, mid+1, high, x);
return findCrossOver(arr, low, mid-1, x);
}
void interp1(double xp[], double yp[], int xyplen, double x[], int xlen,double* y)
{
int index;
int i;
for (i=0; i<xlen; i++)
{
index = findCrossOver(xp, 0, xyplen-1, x[i]);
if(x[i] > xp[xyplen-1])
{
index--;
}
y[i] = ((x[i]-xp[index])*(yp[index+1]-yp[index]))/(xp[index+1]-xp[index]) + yp[index];
}
}
void fpr(double step, double* oldVal, double* xp, double* yp, double* x)
{
int i;
int xyplen = 5; //array sizes through many calculations inside the function
int xylen = 10;
for(i=0; i<xyplen; i++)
{
xp[i] = i+1;
yp[i] = 2*xp[i];
printf("%f\n", xp [i]);
}
for (i=0; i<xylen; i++)
{
x[i] = i+0.5;
}
interp1(xp, yp, xyplen, x, xylen,oldVal);
}
int main()
{
double *someVal=malloc(sizeof(double));
double *yp=malloc(sizeof(double));
double *xp=malloc(sizeof(double));
double *x=malloc(sizeof(double));
fpr(1.1,someVal, xp, yp, x);
printf("%d\n", sizeof(xp)/sizeof(xp[0]));
int i;
printf("Input Data\n");
for (i=0; i<5; i++)
{
printf("(%.1f, %.1f)\t", xp[i], yp[i]);
}
printf("Interpolated Data\n");
for (i=0; i<10; i++)
{
printf("(%.1f, %.1f)\t",x[i],someVal[i]);
}
return 0;
}
And this is the output (due to the printf commands):
1.000000
2.000000
3.000000
4.000000
5.000000
0
Input Data
(-14.5, 0.5) (-22.0, -7.0) (90.5, -14.5) (653.0, -22.0) (89.5, 90.5)
Interpolated Data
(90.5, -3.5) (653.0, -2.5) (89.5, 0.5) (-9.1, -7.0) (4.5, -14.5) (5.5, -22.0) (6.5, 90.5) (7.5, 653.0) (8.5, 89.5) (9.5, -9.1)
As you see the sizeof is just giving the first element address and output in main is not as expected.
sizeofon the function argument you get the size of the pointer and not the array it points to. Not that you have array anyway, you only have pointers to a single value.