动态内存分配的错误结果
Wrong results with dynamic memory allocation
我正在尝试通过程序找出拉格朗日插值。我已经使用数组解决了它,但是当使用动态内存分配时,程序给出了垃圾结果。
#include<stdio.h>
#include<conio.h>
#define SIZE 100
int main()
{
float *x,*y;
float value = 0,ask,temp;
int i,j,n;
printf("Enter size");
scanf("%d",&n);
x = (float*)malloc(n*sizeof(float));
y = (float*)malloc(n*sizeof(float));
for(i = 0; i < n;i++)
{
printf("x[%d]: ",i);
scanf("%f",(x+i));
printf("y[%d]: ",i);
scanf("%f",(y+i));
}
printf("Enter value to find");
scanf("%f",&ask); //cin >> ask;
for(i = 0; i < n;i++)
{
temp = 1;
for(j = 0; j < n; j++)
{
if(i != j)
{
temp = temp * (ask-(*(x+i))/(*(x+i)-*(x+j)));
}
}
value = value + temp * *(y+i);
}
printf("%f",value);
}
您需要 #include <stdlib.h>
,因为那是声明执行动态内存分配(malloc()
等)的函数的 header。
假设您使用的是 C 编译器而不是 C++ 编译器,您会发现 malloc()
调用不需要类型转换。
x = (float*)malloc(n*sizeof(float)); /* (float *) is unnecessary */
问题是,如果没有 stdlib.h
,编译器会假设 malloc()
returns 和 int
。类型转换可能允许代码在没有 stdlib.h
的情况下编译,但结果是 malloc()
d 指针的后续使用将具有未定义的行为,因为指针不一定在往返过程中存活(被转换为int
然后返回)。
如果您使用的是 C++ 编译器,则需要 (float *)
类型转换和 #include <stdlib.h>
来避免未定义的行为。
我正在尝试通过程序找出拉格朗日插值。我已经使用数组解决了它,但是当使用动态内存分配时,程序给出了垃圾结果。
#include<stdio.h>
#include<conio.h>
#define SIZE 100
int main()
{
float *x,*y;
float value = 0,ask,temp;
int i,j,n;
printf("Enter size");
scanf("%d",&n);
x = (float*)malloc(n*sizeof(float));
y = (float*)malloc(n*sizeof(float));
for(i = 0; i < n;i++)
{
printf("x[%d]: ",i);
scanf("%f",(x+i));
printf("y[%d]: ",i);
scanf("%f",(y+i));
}
printf("Enter value to find");
scanf("%f",&ask); //cin >> ask;
for(i = 0; i < n;i++)
{
temp = 1;
for(j = 0; j < n; j++)
{
if(i != j)
{
temp = temp * (ask-(*(x+i))/(*(x+i)-*(x+j)));
}
}
value = value + temp * *(y+i);
}
printf("%f",value);
}
您需要 #include <stdlib.h>
,因为那是声明执行动态内存分配(malloc()
等)的函数的 header。
假设您使用的是 C 编译器而不是 C++ 编译器,您会发现 malloc()
调用不需要类型转换。
x = (float*)malloc(n*sizeof(float)); /* (float *) is unnecessary */
问题是,如果没有 stdlib.h
,编译器会假设 malloc()
returns 和 int
。类型转换可能允许代码在没有 stdlib.h
的情况下编译,但结果是 malloc()
d 指针的后续使用将具有未定义的行为,因为指针不一定在往返过程中存活(被转换为int
然后返回)。
如果您使用的是 C++ 编译器,则需要 (float *)
类型转换和 #include <stdlib.h>
来避免未定义的行为。