2012-09-12 102 views
0

這裏是我的代碼:爲什麼結構,錯誤原因分段故障

struct queue { 
     int queue_arr[5]; 
     int rear; 
     int front; 
}; 

int main() 
{ 
     struct queue q; 
     int choice; 

     queue_init(q); 
} 

queue_init(struct queue *q) 
{ 
     int i = 0; 
     q->rear = -1; 
     q->front = -1; 
     for (; i < MAX; i++) { 
       q->queue_arr[i] = 0; 
     } 
} 

它會導致在執行分段錯誤:

[[email protected] test_cpp]# ./queue Segmentation fault (core dumped) 

如果我刪除結構我將使用int queue_arr[5]; int rear; int front;作爲全球細分誤差消失。爲什麼?以及如何避免它使用結構體白衣?

+0

什麼是'''MAX'''? – tangrs

+0

對不起,#define MAX 5. – rdo

回答

6

您應該通過地址:

queue_init(&q); 
     ^

我很驚訝,它編譯,因爲它主張。

+0

它有幫助,謝謝! – rdo

+1

''queue_init()'在'main()'中被調用之前未被聲明。也許這可以讓編譯成功,並帶有警告? – hmjd

+0

@hmjd *非常好,謝謝! – cnicutar