[英]Segmentation fault copying tree nodes into array
我將這種結構用於我的樹:
typedef struct product{
char name[50];
char id[5];
double price;
int amount;
struct product *left_p, *right_p;
}product_t;
因此,我必須將樹轉換為數組。 我為樹尺寸寫了這個:
int tree_dim(product_t *node_p){
int i = 1 ;
if (node_p == NULL)
i = 0;
else{
i += tree_dim(node_p->left_p);
i += tree_dim(node_p->right_p);
}
return i;
}
通過從txt文件讀取記錄來填充我的樹。 記錄為21,並且tree_dim返回的值正確。 該值存儲在arr_dim
。
然后我創建一個product_t *products_a;
wich將是“數組”,並通過使用products_a = malloc (arr_dim*sizeof (product_t));
在內存中分配它products_a = malloc (arr_dim*sizeof (product_t));
現在,這是用樹節點填充數組的函數:
void fill_array(int *index, product_t *node_p, product_t *products_a){
if (node_p != NULL){
fill_array(index, node_p->left_p, products_a);
products_a[*index++] = *node_p;
fill_array(index, node_p->right_p, products_a);
}
}
但這給了我分段錯誤錯誤,所以我也嘗試了第二種解決方案:
int fill_array(product_t *node_p, product_t *products_a){
int i = 1 ;
if (node_p == NULL){
i=0;
}
else
{
i += fill_array(node_p->left_p, products_a);
products_a[i-1] = *node_p;
i += fill_array(node_p->right_p, products_a);
}
return i;
}
這不會導致分割錯誤,但是當我打印數組時,有空位置。 我需要一些錯誤提示。 索引和遞歸調用可能存在問題,但我無法弄清楚。
看這兩個運算符的優先級
*index++
++
增量比*
取消引用優先級高嗎?
因此,如果您首先通過sizeof(int)
在內存中移動,那么您將無法再分配的內存中使用,取消引用將導致UB。
如果不確定優先級,最好使用方括號()
。
(*index)++ // This is right
Filip已經指出您第一個功能的問題。
第二個函數的問題在於它僅在從左分支填充時才起作用。 完成此操作並復制當前產品后,數組中將包含一些元素,但是從右側分支進行的復制將再次從索引0開始,因此它將覆蓋現有數據,並保留未初始化的數據。
您可以通過將當前索引i
傳遞給函數來解決此問題,但是我發現i = func(..., i);
語法有點多余。
在C語言中,您可以傳入以&array[i]
開頭的元素i
或array + i
開頭的array
的子array
。 (請記住,函數調用中的數組會“衰減”到指向第一個元素&array[0]
的指針中。)
所以這將工作:
int fill_array(product_t *node_p, product_t *products_a)
{
int i = 0;
if (node_p == NULL) return 0;
i += fill_array(node_p->left_p, products_a);
products_a[i++] = *node_p;
i += fill_array(node_p->right_p, &products_a[i]);
return i;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.