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

Huy*_* Le 0 c struct pointers pass-by-reference

    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;
}
Run Code Online (Sandbox Code Playgroud)

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

一种解决方案是编写:

int *tree = heap->tree;
int *pos = heap->pos;
float *p = heap->p;
Run Code Online (Sandbox Code Playgroud)

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

ric*_*ici 7

您可以使用C99 的指定初始化语法来初始化结构:

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))
    };
}
Run Code Online (Sandbox Code Playgroud)