C 如何在不重复使用 -> 的情况下访问结构元素?

C how to access structure elements without using -> repeatedly?

    struct Heap {
        int capacity;
        int heapSize;
        int *tree;     // the heap binary tree
        int *pos;       // pos[i] is the position of values[i] in items
        float *p;  // priority value of each heap element
    };

    void initHeap(struct Heap *heap, int capacity) {
        heap->capacity = capacity;
        heap->heapSize = 0;
        heap->tree = malloc(sizeof(int)*(capacity+1));
        heap->pos = malloc(sizeof(int)*(capacity+1));
        heap->p = malloc(sizeof(float)*(capacity+1));
    }

    void betterInit(struct Heap *heap, int capacity) {
        with (heap) { // doesn't exist
            capacity = capacity;
            heapSize = 0;
            tree = malloc(sizeof(int)*(capacity+1));
            pos = malloc(sizeof(int)*(capacity+1));
            p = malloc(sizeof(float)*(capacity+1));
        }
    }
// update heap after a value is increased
void upHeap(struct Heap *heap, int i) {
    int *tree = heap->tree, *pos = heap->pos;
    float *p = heap->p;
    int c, r;

    c = pos[i];         // position of element i-th in heap
    while (true) {
        r = parent(c);
        if (r==0 || p[tree[r]] >= p[i]) break; // if c is root, or priority(parent(c)) is > priority(c)
        pos[tree[r]] = c;  // pull the parent down to c
        tree[c] = tree[r];
        c = r;
    }
    tree[c] = i;
    pos[i] = c;
}

所以第一个 initHeap 看起来很长,因为我必须写很多次 heap->。我想让它看起来更短。

一个解决方案是这样写:

int *tree = heap->tree;
int *pos = heap->pos;
float *p = heap->p;

然后使用tree, pos, p。还有更多方法吗?

使用点“.”怎么样? ? 喜欢

struct Heap {
    int capacity;
    int heapSize;
    int *tree;     // the heap binary tree
    int *pos;       // pos[i] is the position of values[i] in items
    float *p;  // priority value of each heap element
}H; //to make abbreviation for Heap

然后使用

H.capacity = capacity;
H.heapsize = 0;

您可以使用 C99's designated initialiser 语法初始化结构:

void initHeap(struct Heap *heap, int capacity) {
    *heap = (struct Heap){
        .capacity = capacity,
        .heapSize = 0,
        .tree = malloc(sizeof(int)*(capacity+1)),
        .pos = malloc(sizeof(int)*(capacity+1)),
        .p = malloc(sizeof(float)*(capacity+1))
    };
}

好的旧宏呢?

struct Heap {
    int capacity;
    int heapSize;
    int *tree;     // the heap binary tree
    int *pos;       // pos[i] is the position of values[i] in items
    float *p;  // priority value of each heap element
};

#define _(x) heap->x
void initHeap(struct Heap *heap, int capacity) {
    _(capacity) = capacity;
    _(heapSize) = 0;
    _(tree) = malloc(sizeof(int)*(capacity+1));
    _(pos) = malloc(sizeof(int)*(capacity+1));
    _(p) = malloc(sizeof(float)*(capacity+1));
}
/* More struct Heap related functions */
#undef _

如果以一种有规律的方式使用并且在这个库的实现中有简洁的代码,我不觉得这是一个坏主意。而且,作为奖励,它也适用于部分更新和在 C++ 编译器中导入时(我知道这看起来不是很重要)。

顺便说一句,为什么 capacity+1malloc() 的调用中?