c - 指针魔术: structs with pointer members and more

标签 c pointers struct

我真的不知道如何给这个问题一个好的标题 - 对此感到抱歉。

只是为了知道这一切的目标是什么:将 uint8_t 变量指针传递给 bar() ,它将其设置为 1 或 0,以便我可以检查它在我的 main.c 中的状态。我确实需要 zbar(),它是一个线程,它实际上将值设置为 1 或 0

所以我有一个地方:

struct foo_t {
    ...
    uint8_t *state;
};

主要是我选择:

int main(void) {
     uint8_t state = 0;
     bar(&state);

     while(1) {
          if(state)
              //do something here
     }
}

这里我们在另一个源文件的其他地方。

void bar(uint8_t *state) {
    struct foo_t *foo;    //using malloc here - don't worry

    foo->state = state;

    zbar(foo); 

}

void zbar(struct foo_t *arg) {
    if(condition)
       arg->state = 1;
    else
       arg->state = 0;
 }

如何使其发挥作用? 00 zBar 实际上可以访问 arg 结构,这根本不是问题。

请不要担心我为什么这样做这么奇怪,它是在线程等中使用的。

最佳答案

我假设你的意思是void bar(uint8_t* state)

它没有达到我认为你想要的效果。我再次假设您希望更改 main 中的 state 变量?如果是这样尝试

struct foo_t {
    uint8_t* state; // changed this to a pointer type.
}

void bar(uint8_t* state) {
    struct foo_t *foo = blah blah;
    foo->state = state;
    zbar(foo);
}

void zbar(foo_t* arg) {
   if (condition)
       *(arg->state) = 1;
   else
       *(arg->state) = 0;
}

认为这就是你想要做的

关于c - 指针魔术: structs with pointer members and more,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10935300/

相关文章:

c++ - 给指针赋值抛出异常

c - 理解 C 结构

c - 删除链表中M个节点后的N个节点

关注结构指针

pointers - Go struct literals,为什么这个是可寻址的?

arrays - 如何使用映射分配结构类型值?

c - 变量的双重定义

c - 错误 : called object ‘0’ is not a function

将以太网地址转换为可读形式?

ios - 代码 : Working In ARC and NSArrays