【发布时间】:2015-07-27 16:14:45
【问题描述】:
我正在尝试用 C 编写一个函数来初始化多个具有不同大小的双精度类型数组。数组大小应在函数中给出,数组值通过先前定义的函数和值分配。 这些功能将被设置为无效,因为我以后应该在不同的地方多次使用它们。这是一个没有给出合理结果的代码版本。感谢您的帮助!
#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;
}
这是输出(由于 printf 命令):
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)
如您所见,sizeof 只是给出了第一个元素的地址,而 main 中的输出并不像预期的那样。
【问题讨论】:
-
这个肯定有很多重复,但简短的回答是,当你将一个数组传递给一个函数时,它衰减到一个指针,所以当你这样做时
sizeof在函数参数上,您获得指针的大小,而不是它指向的数组。并不是说你有数组,你只有指向 single value. 的指针
标签: c arrays function pointers initialization