簡體   English   中英

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

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

我必須創建一個 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;
}

我得到的 output 是

 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 function 但我無法弄清楚問題是什么

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