猿问

C语言链表问题 出现段错误

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#define MAXLEN 100
struct zahlen{
   double wert;
   struct zahlen *next;
};
int main(int argc, char *argv[])
{
   FILE *datei;
   char zeile[MAXLEN];
   int nz;
   double zahl;
   int rc;
   char *start;
   struct zahlen *root, *curr;
   double summe;
   double mittelwert;
   double max,min;
   double standardabweichung;
   if(argc < 2){
       fprintf(stderr, "Fehlender Dateiname\n");
       exit(1);
   }
   if(datei = fopen(argv[1], "r"), datei == NULL){
       perror(argv[1]);
       exit(1);
   }
   nz = 0;
   while(fgets(zeile, MAXLEN, datei) != NULL){
       start = zeile;
       while(*start && strchr("0123456789", *start) == NULL)
           start++;
       rc = sscanf(start, "%lf", &zahl);
       if(rc != 1)
           continue;
       printf("%d. Messwert: %7.3lf\n", nz+1, zahl);
       nz++;
       /*Dynamische Speichernutzung*/
       if(root == NULL){
           root = calloc(1, sizeof(struct zahlen));
           if (root == NULL){
               perror("calloc");
               exit(1);
           }
           root->wert = zahl;
           root->next = NULL;
           curr = root;
       }
       else{
           curr->next = calloc(1, sizeof(struct zahlen));
           if(curr->next == NULL){
               perror("calloc");
               exit(1);
           }
           curr = curr->next;
           curr->wert = zahl;
           curr->next = NULL;
       }
   }
   if(!feof(datei)){
       perror(argv[1]);
       exit(1);
   }
   printf("Das waren %d Messwerten\n", nz);
   fclose(datei);
   curr = root;
   summe = 0;
   while(curr != NULL){
       summe += curr->wert;
       curr = curr->next;
   }
   mittelwert = summe / (double)nz;
   printf("Summe: %7.3lf\n", summe);
   printf("Mittelwert: %7.3lf\n", mittelwert);
   curr = root;
   min = 0;
   max = 0;
   while(curr != NULL){
       if(curr->wert > max)
           max = curr->wert;
       if(curr->wert < min)
           min = curr->wert;
       curr = curr->next;
   }
   printf("Max. Messwert: %7.3lf\n", max);
   printf("Min. Messwert: %7.3lf\n", min);
   curr = root;
   standardabweichung = 0;
   while(curr != NULL){
       standardabweichung += pow((curr->wert - mittelwert), 2);
       curr = curr->next;
   }
   standardabweichung = sqrt(standardabweichung / ((double)(nz - 1)));
   printf("Standardabweichung: %7.3lf\n", standardabweichung);
   return 0;
}

//如题,功能是读取文件中的数,每行都有一个数字,也会有单位
//因为题主在德国,所以有些变量设置用了德文单词,请见谅!




way_shine
浏览 1947回答 2
2回答

onemoo

第二个if处: if(datei = fopen(argv[1], "r"), datei == NULL)这里应该用逻辑与&&连接前后两个条件,你写成逗号了。 这样括号中就将datei赋值为NULL了,并且整个表达式也为false,结果这个if中的内容就被跳过了,所以你没有收到perror(argv[1])的报错信息。后面代码再操作NULL指针就容易引起段错误。

DoDream

可以将段错误和文件内容截图看一下吗
随时随地看视频慕课网APP
我要回答