Pointer auf Struct "*.exe funktioniert nicht mehr"
-
Hallo,
ich muss ein Programm schreiben mit Poitern auf Structs die selber auch wieder Poointer haben und dann bekomme ich die Fehlermeldung "motneCarlo.exe funktioniert nicht mehr.". Wenn ich in der readIn.c vone Zeile 17 bis 24 alles auskommentiere stürtzt es nicht mehr ab, aber ich finde den Fehler nicht. Das ganze besteht, bis jetzt, aus vier Dateien (monteCarlo.c, adt.h, readIn.c und readIn.h), es soll aber noch größer werden.adt.h
typedef struct{ int degree; double *coefficients; double constant; }polynomial;monteCarlo.c
#include <stdio.h> #include "adt.h" #include "readIn.c" int main(void){ int i; polynomial *polyStruct; results *resStruct; settings *setStruct; readIn(polyStruct, setStruct); /*free memory from malloc in readIn.c*/ free(polyStruct->coefficients); return (0); }readIn.c
#include <stdlib.h> #include "readIn.h" void readIn(polynomial *polStrPoi, settings *setStrPoi){ /*Init*/ int i; /*read the data for polynomial struct*/ /*read the degree*/ printf("Please enter the degree of the polynomial: "); scanf("%d", &polStrPoi->degree); printf("\n"); /*allocate memory for the coefficients*/ (*polStrPoi).coefficients = (double *) malloc ( (*polStrPoi).degree * sizeof(double)); /*enter the coefficients*/ for(i=0; i < (polStrPoi->degree); i++) { printf("Please enter coefficient %d: ", (i+1) ); scanf("%f", &polStrPoi->coefficients[i]); } /*enter the constant*/ printf("\nPlease enter the constant of the polynomial: "); scanf("%f", &polStrPoi->constant); }readIn.h
void readIn(polynomial *polStrPoi, settings *setStrPoi);Könnt ihr mir helfen? Ich dreh noch durch...
-
Mit
polynomial *polyStruct; results *resStruct; settings *setStruct;legst du nur ein paar Zeiger auf den Stack; du hast damit keinen Speicher für die eigentlichen Structs angefordert. Wenn später in readIn darauf zugegriffen wird, gehen die Zugriffe ins Nirvana und du kriegst Segfaults.
Richtig wäre
/* Hier Structs statt Zeiger anlegen */ polynomial polyStruct; settings setStruct; /* Und hier ihre Adressen übergeben */ readIn(&polyStruct, &setStruct);
-
Danke für die schnelle, gute und einfache Antowort
