Dynamische int Array in struktur erstellen??
-
Hallo @ all!
Folgender Code:
Mein Struckt:
typedef struct { char *id; int *x; int *y; }polygon;
Meine Funktion:
void polygon_input() { polygon tmp_polygon; }
In der Funktion werden verschiedene x werte eingelesen ich weiß nicht in vorraus wieviele es sind und daher will ich ein dynamischen array im struckt erstellen die id ändert sich dabei nicht!
So hab ich es versucht:count++; tmp_polygon.x = malloc(sizeof(int)); tmp_polygon.x = realloc((tmp_polygon.x), count +2); tmp_polygon.x[count] = igendein_wert; count++;
Aber irgenwie Funktioniert nicht dieser Zugriff!! Warum nur?? Kann mir jemand weiterhelfen?
mfg
-
hanni6al schrieb:
Aber irgenwie Funktioniert nicht dieser Zugriff!!
Das ist keine Fehlerbeschreibung! Was funktioniert nicht? Wann findet ein Fehler statt? Compile- oder Runtime? Welche Fehlermeldung?
-
Also wenn ich die Eingelesen werte so zuweisen will:
tmp_polygon.x[count] = 3; count++; tmp_polygon.x[count]= 6;
dann werden sie einfach nicht im struct gespeichert!! Und nach einigen solcher zuweisungen kommt immer eine zugriffsverletzen!!
-
Geh mit dem Debugger schrittweise durch und überprüfe, auf welchem Wert count z.B. beim ersten Schreiben ins struct steht. Es kommt mir schon komisch vor, dass du count inkrementierst (count++), bevor du Speicher allozierst und Werte speicherst. Du solltest ja schließlich beim Index 0 anfangen, zu schreiben.
-
Ok das hab ich wegelassen ich mache es so:
int count = 0; polygon tmp_polygon; tmp_polygon.x = malloc(sizeof(int)); tmp_polygon.x = realloc((tmp_polygon.x), count +2); tmp_polygon.x[count] = igendein_wert; count++; tmp_polygon.x = realloc((tmp_polygon.x), count +2); tmp_polygon.x[count] = igendein_wert; count++;
Bin es auch mit den debugger durchgegangen und es werden einfach nicht die Werte in das struct geschrieben.
Das Struct:
typedef struct { char id; int *x; }polygon
-
struct polygon { char id; int *x; // array int y; // wert };
void polygon_input() { polygon tmp_polygon; }
count++; int anzahl_der_felder = 10; tmp_polygon.x = malloc(anzahl_der_felder * sizeof(int)); tmp_polygon.x[count] = igendein_wert; count++;
Habs jetzt nicht getestet, aber vielleicht klappt es ja auf Anhieb.
mfg