我試圖將結構複製到結構數組中。將結構複製到動態分配的結構數組中
我有一個具有頂點的動態分配的數組稱爲
vlist
和一個整數存儲在所述VLIST頂點的數量的字段的圖結構。
頂點有一個名稱數組作爲它們的內部字段。 函數我得到一個錯誤,需要一個圖形和一個字符串,並將一個頂點添加到該圖形中,該字符串作爲頂點的名稱。
下面是函數:
int add_vertex(Graph *graph, const char name[]){
if(name && graph){
/*Allocating space for new vertex*/
vertex *new_vert = malloc(sizeof(vertex));
/*Allocating space for vertex name*/
new_vert->name = malloc(strlen(name)+1);
/*Copying new vertex name to newly allocated vertex*/
strcpy(new_vert -> name, name);
/*Adding a new space to vertex list*/
graph -> vlist = realloc(graph-> vlist, sizeof(graph -> vlist) + sizeof(vertex));
graph -> num_verts += 1;
graph -> vlist[graph->num_verts] = new_vert;
return 1;
}
else{
return 0;
}
我收到錯誤行:
graph -> vlist[graph->num_verts] = new_vert;
錯誤:
incompatible types when assigning to type 'vertex' from type 'struct vertex *'
我假設這意味着我」 m錯誤地將值複製到動態數組中,但我無法弄清楚原因。
我的頂點在頭文件中定義爲:
typedef struct vertex{
char *name;
} vertex
任何幫助都將是巨大的,謝謝!
編輯:
圖表
typedef struct Graph {
vertex *vlist;
int num_verts;
} Graph;
對於Graph和vlist是什麼,我懷疑sizeof(graph - > vlist)是指針的大小,而不是指向的數組的大小。顯然'realloc(graph-> vlist,sizeof(graph - > vlist)+ sizeof(vertex));'是錯誤的。 –
爲什麼不復制和粘貼它,而不是用英文描述'Graph'的刪除? – Neo
'graph - > vlist [graph-> num_verts] = * new_vert;'? –