2017-12-01 7 views
0

Ich versuche Cluster mit dynamischen Array-Objekten zu erstellen.C - Zugriff auf dynamisches Array innerhalb einer Struktur

Struct Definitionen sind folgende:

struct obj_t { 
    int id; 
    float x; 
    float y; 
}; 

struct cluster_t { 
    int size; 
    int capacity; 
    struct obj_t *obj; 
}; 

Funktionsobjekt zu Cluster zum Hinzufügen ist:

void append_cluster(struct cluster_t *c, struct obj_t obj) 
{ 
    if(c->capacity < (c->size + 1)) 
    { 
     c = resize_cluster(c, c->size + 1); 
    } 
    if(c == NULL) 
     return; 
    c->obj[c->size] = obj; //at this point program crashes. 
    c->size++; 
} 

EDIT: Hier ist resize_cluster() Funktion:

struct cluster_t *resize_cluster(struct cluster_t *c, int new_cap) 
{ 
    if (c->capacity >= new_cap) 
     return c; 

    size_t size = sizeof(struct obj_t) * new_cap; 

    void *arr = realloc(c->obj, size); 
    if (arr == NULL) 
     return NULL; 

    c->obj = (struct obj_t*)arr; 
    c->capacity = new_cap; 
    return c; 
} 

EDIT 2: Hier ist die Cluster-Initialisierung:

void init_cluster(struct cluster_t *c, int cap) 
{ 
    c = malloc(sizeof(struct cluster_t)); 
    c->size = 0; 
    c->capacity = cap; 
    c->obj = (struct obj_t*)malloc(cap * sizeof(struct obj_t)); 
} 

Ich kann nicht herausfinden, warum Programm abstürzt, wenn ich versuche, das Objekt dem Array im Cluster hinzuzufügen. Ist der Zugriff auf das Array falsch? Wenn ja, wie sollte ich darauf zugreifen?

+1

Können wir see'resize_cluster() '? –

+2

Wie initialisierst du deine cluster_t? – EdmCoff

+0

Fragen, die Debugging-Hilfe suchen ("Warum funktioniert dieser Code nicht?") Müssen das gewünschte Verhalten, ein bestimmtes Problem oder einen Fehler und den kürzesten Code enthalten, der für die Reproduktion in der Frage erforderlich ist. Fragen ohne eine klare Problemstellung sind für andere Leser nicht nützlich. Siehe: Erstellen eines [mcve]. – AndyG

Antwort

3

Das Problem ist der Anruf an init_cluster(). Die c Parameter übergeben-by-Wert, so was auch immer Sie senden bleibt unverändert:

struct cluster_t * c; 
init_cluster(c, 1); 
// c is uninitialized! 

Ein fix einen Zeiger auf ein Objekt zu übergeben wäre:

struct cluster_t c; 
init_cluster(&c, 1); 

Dann entfernen c = malloc(sizeof(struct cluster_t)); von init_cluster();

Oder könnten Sie eine alloc_cluster Funktion erstellen:

struct cluster_t * alloc_cluster(int cap) 
{ 
    c = malloc(sizeof(struct cluster_t)); 
    c->size = 0; 
    c->capacity = cap; 
    c->obj = malloc(cap * sizeof(struct obj_t)); 
    return c; 
} 

Und nennen Sie es wie:

struct cluster_t *c = init_cluster(1); 
+0

Entfernen von 'c = malloc (sizeof (struct cluster_t));' von 'init_cluster()' funktioniert wie ich wollte. Danke vielmals. – user3670471

Verwandte Themen