Structs! Brauche dringend Hilfe!!



  • Hallo @ all!!

    Brauche dirngend Hilfe bei Structs folgendes!!

    Mein Struct:

    typedef struct _Polygon_
    {
    	int *x;
    }Polygon;
    

    Da ich mehrere x und y werte habe erstelle ich ein dynamisches array

    int main()
    {
    
    Polygon pol;
    
    pol.x = malloc(sizeof(int));
    pol.x[0]= 10;
    
    pol.x = realloc(pol.x, 3 * sizeof(int));
    pol.x[1] = 20;
    pol.x[2]= 30;
    pol.x[3]= 50;
    
    ausgabe(); => funktion zur ausgabe;
    
    return 0;
    }
    

    Und jetzt möchte ich in der funktion meine eingelesen Werte ausgeben:

    ausgabe()
    {
      Polygon pol;
      printf("%d", pol.x[2]);
    }
    

    Aber das funktioniert einfach nicht!!! WARUM NICHT 😡 😡 ich komme einfach nicht weiter wäre sehr dankbar wenn mir jemand dabei helfen könnte!!



  • Verdächtig: Du reallocst 3 ints Speicher, greifst aber auf den vierten zu (pol.x[3]).



  • noch mehr verdächtig:

    ausgabe()
    {
      Polygon pol;
      printf("%d", pol.x[2]);
    }
    

    pol ist funktionslokal.



  • 1. Mit funktionslokal meint sothis, dass du ein neues Objekt lokal in deiner Funktion erzeugst, dass mit dem übergeordneten nix zu tun hat, auch wenn es denselben Namen trägt. Übergib einen Pointer auf pol an deine Funktion.

    2. "funktioniert einfach nicht" ist keine Fehlerbeschreibung, auch wenn es in diesem Fall klar ist.

    3. Du benutzt malloc/realloc ohne free! D.h., du produzierst hier Speicherlecks! Gewöhn dir am besten an, zu jedem malloc direkt das free zu notieren.


Anmelden zum Antworten