简体   繁体   English

在我调用返回 C 中的指针的 function 后程序停止工作

[英]Program stops working after i call a function that returns a pointer in C

I have to create a function that, given 2 different values s1 and s2 (s1<s2) and a vector filled by a file, creates a new vector and arranges the values (a) of the first vector putting the a<s1 elements at the start of the new vector, followed up by the values s1< a < s2 and in the end the values a>s2 and prints the initial vector and the new one我必须创建一个 function,给定 2 个不同的值 s1 和 s2 (s1<s2) 以及一个由文件填充的向量,创建一个新向量并排列第一个向量的值 (a),将 a<s1 元素放在新向量的开始,后面是值 s1< a < s2,最后是值 a>s2 并打印初始向量和新向量

#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;
}

the output i get is我得到的 output 是

 10.00      2.30      4.56      2.00      1.23      8.65     10.00    -12.30      4.34     16.22      2.30

so the program only prints the first vector and stops working after所以程序只打印第一个向量并在之后停止工作

 printVect(Ptr); 
    puts("\n");

i guess the problem is with the functB function but i can't figure out what the problem is我想问题出在 functB function 但我无法弄清楚问题是什么

Within functB , you return and mutate the newVect that is defined but not initialized.functB中,您返回并改变已定义但未初始化的newVect

double *newVect = malloc (DIM*sizeof(double));

if (!newVect) generate_error_and_return();

else your code.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM