在另一个静态结构中静态分配struct成员?

时间:2015-11-15 05:26:20

标签: c struct static-members

我试图在不使用动态内存分配的情况下实现低级线程锁;这段代码基本上可以用在完全简单的内核上。

但是,当我试图取消引用此全局静态结构中的成员时,我遇到了接收seg错误的问题。我的代码是这样的

我的包装结构

/** LOCKING STRUCT & FUNCTIONS **/
struct lock {
    int free;
    struct thread_list* wait_list;
    struct thread* current_holder;
};

嵌套结构(用作链接列表的交易)

struct thread_list {
    struct thread *head;

};

此列表中的成员

struct thread {
    void *top; // top of the stack for this thread
    void *sp;  // current stack pointer for this thread (context)
    void (*start_func)(void *);
    void *arg;
    int state;
    int exit_value;
    struct thread *join_thread;
    struct thread *next_thread;
    int id;
};

我试图实施的方法就是这样

void lock_init (struct lock *lk) {
    lk->free = 1; //Set lock as free
    struct thread_list waiting = lk->wait_list; //Get waitlist, works fine
    waiting->head = NULL; //Set waitlist's head to null, SEGFAULTS HERE
}

我不是非常精通C,但我似乎无法找出正确的方法/语法来使我的代码像这样工作。

1 个答案:

答案 0 :(得分:1)

struct thread_list waiting = lk->wait_list; //Get waitlist, works fine
waiting->head = NULL; //Set waitlist's head to null, SEGFAULTS HERE

waiting不是结构指针而是结构变量。要使用它访问成员,您需要使用.运算符 -

 waiting.head = NULL;

或者使用->运算符将其声明为结构指针。