在我调用一个 returns C 中的指针的函数后程序停止工作
Program stops working after i call a function that returns a pointer in C
我必须创建一个函数,给定 2 个不同的值 s1 和 s2 (s1s2 并打印初始向量和新向量
#include <stdio.h>
#include <stdlib.h>
#define DIM 11
void printVect(double *);
double *functB(double *vectPtr);
int main()
{
FILE *fp;
double vect[DIM], *Ptr;
double newvect[DIM], *nvPtr;
Ptr=(double*) malloc(sizeof(double)*DIM);
fp=fopen("dati.txt", "r");
for(int i=0; i<DIM; i++)
{
fscanf(fp, "%lf", &Ptr[i]);
}
printVect(Ptr);
puts("\n");
*newvect=*functB(Ptr);
printVect(newvect);
}
void printVect(double *vector)
{
for(int i=0; i<DIM; i++)
{
printf("%10.2lf", vector[i]);
}
}
double *functB(double *vectPtr)
{
int s1=2; int s2=5; int n=0;
double *newVect;
for(int i=0; i<DIM; i++)
{
if(vectPtr[i]<s1)
{
newVect[n]=vectPtr[i];
n++;
}
}
for(int i=0; i<DIM; i++)
{
if(vectPtr[i]<s2 && vectPtr[i]>s1)
{
newVect[n]=vectPtr[i];
n++;
}
}
for(int i=0; i<DIM; i++)
{
if(vectPtr[i]>s2)
{
newVect[n]=vectPtr[i];
n++;
}
}
return newVect;
}
我得到的输出是
10.00 2.30 4.56 2.00 1.23 8.65 10.00 -12.30 4.34 16.22 2.30
所以程序只打印第一个向量并在
之后停止工作
printVect(Ptr);
puts("\n");
我想问题出在 functB 函数上,但我不知道问题出在哪里
在 functB
中,您 return 并改变已定义但未初始化的 newVect
。
double *newVect = malloc (DIM*sizeof(double));
if (!newVect) generate_error_and_return();
else your code.
我必须创建一个函数,给定 2 个不同的值 s1 和 s2 (s1
#include <stdio.h>
#include <stdlib.h>
#define DIM 11
void printVect(double *);
double *functB(double *vectPtr);
int main()
{
FILE *fp;
double vect[DIM], *Ptr;
double newvect[DIM], *nvPtr;
Ptr=(double*) malloc(sizeof(double)*DIM);
fp=fopen("dati.txt", "r");
for(int i=0; i<DIM; i++)
{
fscanf(fp, "%lf", &Ptr[i]);
}
printVect(Ptr);
puts("\n");
*newvect=*functB(Ptr);
printVect(newvect);
}
void printVect(double *vector)
{
for(int i=0; i<DIM; i++)
{
printf("%10.2lf", vector[i]);
}
}
double *functB(double *vectPtr)
{
int s1=2; int s2=5; int n=0;
double *newVect;
for(int i=0; i<DIM; i++)
{
if(vectPtr[i]<s1)
{
newVect[n]=vectPtr[i];
n++;
}
}
for(int i=0; i<DIM; i++)
{
if(vectPtr[i]<s2 && vectPtr[i]>s1)
{
newVect[n]=vectPtr[i];
n++;
}
}
for(int i=0; i<DIM; i++)
{
if(vectPtr[i]>s2)
{
newVect[n]=vectPtr[i];
n++;
}
}
return newVect;
}
我得到的输出是
10.00 2.30 4.56 2.00 1.23 8.65 10.00 -12.30 4.34 16.22 2.30
所以程序只打印第一个向量并在
之后停止工作 printVect(Ptr);
puts("\n");
我想问题出在 functB 函数上,但我不知道问题出在哪里
在 functB
中,您 return 并改变已定义但未初始化的 newVect
。
double *newVect = malloc (DIM*sizeof(double));
if (!newVect) generate_error_and_return();
else your code.