[英]Pass struct by reference, return pointer to new struct
I would like to pass a struct to a function by reference, create a new instance of a struct, destroy the original and return a new struct correctly. 我想通过引用将结构传递给函数,创建结构的新实例,销毁原始结构并正确返回新结构。 A specific example of such case is a queue resize function:
这种情况的一个具体示例是队列调整大小函数:
A queue structure itself: 队列结构本身:
// Queue for storage of pairs
typedef struct {
int n; // size of queue
int m; // no. of pairs in queue
int f; // index of front element
int r; // index of rear element
pair *pairs; // array of pairs
} queue;
Queue initialisation routine: 队列初始化例程:
// Initialises queue
int init(int const *n, queue *q) {
q->n = *n;
q->m = 0;
q->f = 0;
q->r = 0;
q->pairs = (pair*) calloc(q->n, sizeof(pair));
return 0;
}
Queue destruction routine: 队列销毁例程:
// Destroys queue
int destroy(queue *q) {
q->n = 0;
q->m = 0;
q->f = 0;
q->r = 0;
free(q->pairs);
return 0;
}
Enqueue routine: 入队例程:
// Adds pair to queue
int enqueue(pair *p, queue *q) {
// resize queue if necessary
if (isfull(q)) int status = resize(q);
if (q->m > 0) q->r = (++q->r) % q->n;
q->pairs[q->r] = *p;
q->m++;
return 0;
}
My take at the queue resizing routine (currently it crashes with a floating point exception). 我对队列调整大小例程的看法(目前它因浮点异常而崩溃)。 I believe to resize a queue correctly I need to pass a pointer to a queue pointer, but so far I am unable to achieve this.
我相信要正确调整队列的大小,我需要将指针传递给队列指针,但是到目前为止,我无法实现这一点。
// Resizes queue
int resize(queue *q) {
// initialise new queue
const int N = 2*q->n;
queue p;
init(&N, &p);
// copy pairs from old to new queue
for (int i = 0; i < q->m; i++) {
pair f = dequeue(q);
enqueue(&f, &p);
}
// destroy old queue
destroy(q);
// re-assign pointer to new queue
q = &p;
return 0;
}
Reassigning the pointer is completely useless. 重新分配指针是完全没有用的。 You changed it locally, but that didn't modify the original object.
您在本地进行了更改,但是并没有修改原始对象。 What you did was destroying the original queue, with nothing left in place.
您要做的是销毁原始队列,什么也没留。
What you want to do is to modify provided object in-place . 您要做的是就地修改提供的对象。
For example: 例如:
*q = p;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.