【问题标题】:calling a function need struct with substruct调用函数需要带有子结构的结构
【发布时间】:2018-11-03 12:11:29
【问题描述】:

我不知道我的标题是否真的很清楚(我真的不知道如何命名)但没关系。我有一个函数,参数中有一个子结构。我在 main 中使用了 struct,但在函数中没有使用,因为该函数内部的无用数据。我的程序是这样的:

typedef struct vidinfo_s {
      vidframe_s sVid;
      int id;
      [...]
};

typedef struct vidframe_s {
      int phyAddr[3];
      char *virAddr[3];
      [...]
};

int function (vidframe_s *pVid)

我的问题是:我需要调用像 int callVidInfo(vidinfo_s *pVid) 这样的函数,但我真的不知道如何使用子结构(因为我命名为 vidframe_s)所以有没有办法做到这一点,或者我必须调用我的function中的主结构?

【问题讨论】:

  • 这很简单:如果你有vidinfo_s vid_info;,那么组件sVid(又名vid_info.sVid)的地址就是&vid_info.sVid
  • 我忘记了 * 运算符
  • 顺便说一句,您的typedefs 毫无意义,因为您没有键入任何内容。 typedef struct vidinfo_s { [...] } sometypename; 是有道理的。

标签: c function structure


【解决方案1】:

是的,有办法。您发布的代码很少,但您可能正在搜索名为offsetofcontainerof 的smth:

#include <stdlib.h>
#include <stddef.h>
#include <stdint.h>
#include <assert.h>

struct vidframe_s {
     int unused; 
};

struct vidinfo_s {
     struct vidframe_s sVid;
     int id; 
};

int callVidInfo(struct vidinfo_s * vidinfo) {
    assert(vidinfo->id == 5);
    return 0; 
}

int function(struct vidframe_s *pVid) {
     const size_t offsetofsVid = offsetof(struct vidinfo_s, sVid);
     struct vidinfo_s * const vidinfo = (struct vidinfo_s*)((char *)pVid - offsetofsVid);
     return callVidInfo(vidinfo); 
}

int main() {
    struct vidinfo_s var = { .id = 5 };
    return function(&var.sVid); 
}

看看我在那里做了什么?我取了struct vidinfo_s 和它的成员sVid 之间的偏移量。然后我从pVid 指针中减去偏移量(它应该指向struct vidinfo_s 结构内),因此我留下了指向struct vidinfo_s 的指针。

【讨论】:

  • 我对 'const' 演员不是很熟悉,它们真的有用吗?
  • 常量左值不能被修改或赋值(仅此而已)。 const 变量不是常量表达式。 const 并不意味着你不能修改变量,只是你不能通过这个句柄修改它(你可以抛弃 const 并修改它)。我主要将 const 用作化妆品 - 告知他人,我不会更改此变量。也许在这个简短的例子中,它们更具误导性而不是帮助。指针中的 const 也位于错误的位置...已编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-31
  • 2011-10-11
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多