c - 通过引用传递结构,返回指向新结构的指针

标签 c pointers struct

我想通过引用将结构传递给函数,创建结构的新实例,销毁原始结构并正确返回新结构。这种情况的一个具体示例是队列大小调整函数:

队列结构本身:

// 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;

队列初始化例程:

// 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;
}

队列销毁例程:

// Destroys queue
int destroy(queue *q) {

    q->n = 0;
    q->m = 0;
    q->f = 0;
    q->r = 0;
    free(q->pairs);

    return 0;
}

排队例程:

// 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;
}

我对队列大小调整例程的看法(目前它因浮点异常而崩溃)。我相信要正确调整队列大小,我需要将指针传递给队列指针,但到目前为止我无法实现这一点。

// 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;
}

最佳答案

重新分配指针是完全没有用的。您在本地更改了它,但并未修改原始对象。你所做的是破坏原来的队列,没有留下任何东西。

您要做的是就地修改提供的对象。

例如:

*q = p; 

关于c - 通过引用传递结构,返回指向新结构的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52708751/

相关文章:

c - 尝试复制到结构元素时出现 MEMCPY 段错误

c - 指针被莫名其妙地修改

c - 使用 Struct 按价格对给定书籍进行排序

c++ - 结构tm时间; vs tm 时间 = {}。输出相同但不一样?

C:从另一个函数返回字符串

c - 我应该如何调整 SQLite 以获得最小延迟?

c++ - 删除 vector 中指针的方法 [C++]

C读取函数未定义错误: 0

在 C 中调用具有较少参数的函数的后果?

c++ - 添加到 vector 或从 vector 中删除后,指向 vector 元素的指针是否保留(在 C++ 中)