[英]Using pointers for queue type
我對c和指針很陌生。 每次我了解了k時,都會遇到一個我並不真正理解的問題(我花了一些時間閱讀c docs,但仍然對我不清楚指針):
typedef struct {
int q[QUEUESIZE+1];
int first;
int last;
int count;
} queue;
enqueue(queue *q, int x)
{
if (q->count >= QUEUESIZE)
printf("Warning: queue overflow enqueue x=%d\n",x);
else {
q->last = (q->last+1) % QUEUESIZE;
q->q[ q->last ] = x;
q->count = q->count + 1;
}
}
我希望我的問題不會太模糊,但是有人可以解釋在入隊函數中使用指針嗎? 我以為排隊的原則是分配一些精確的連續內存地址,但不是肯定的。
enqueue
接受一個隊列隊列(類型為queue的隊列 ),並在其中添加一個元素(由整數組成)。
queue *q
是一個指針,因為
enqueue
后,修改也將保持有效 按值傳遞隊列,如
enqueue(queue q, int x) { ...
意味着
q
參數的副本) q
被修改時,修改在由q
的內enqueue
功能。 最初提供的隊列(myqueue)作為參數不會被修改 例如
enqueue(queue q, int x) {
q.count++; // only the local q.count is changed, not myqueue.count
// ...
}
// ...
queue myqueue;
// ...
enqueue (myqueue, 3); // enqueue changes its local parameter, myqueue is not affected
此外,可以優化入enqueue
功能...(請參閱下面的wildplasser答案,誰建議使用更好的隊列實現)
struct queue {
unsigned first;
unsigned count;
int q[QUEUESIZE];
};
int enqueue(struct queue *q, int x)
{
if (q->count >= QUEUESIZE) {
fprintf(stderr, "Warning: queue overflow enqueue x=%d\n", x);
return -1;
}
q->q[ (q->first+q->count++) % QUEUESIZE ] = x;
return 0; /* success */
}
幾點:
sizeof q->q / sizeof q->q[0]
,它更可靠。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.