Home > Software design >  Program stops working after i call a function that returns a pointer in C
Program stops working after i call a function that returns a pointer in C

Time:02-18

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

#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(".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

 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

CodePudding user response:

Within functB, you return and mutate the newVect that is defined but not initialized.

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

if (!newVect) generate_error_and_return();

else your code.
  • Related