c - calling a function need struct with substruct
问题描述
I don't know if my title is really clear (I don't really know how to named it) but nevermind. I've got a function with a substruct in parameter. I used the struct in the main, but not in the function because of the useless data inside for this function. My program is like that :
typedef struct vidinfo_s {
vidframe_s sVid;
int id;
[...]
};
typedef struct vidframe_s {
int phyAddr[3];
char *virAddr[3];
[...]
};
int function (vidframe_s *pVid)
My question is : I need to call a function like int callVidInfo(vidinfo_s *pVid)
but I don't really know how to do it with the substruct (as I named vidframe_s) so is there a way to do that or must I call my main struct in function
?
解决方案
是的,有办法。您发布的代码很少,但可能您正在搜索称为offsetof或containerof的东西:
#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
.
推荐阅读
- angular - 嵌套的 Angular 模块:无法从 npm 包中解析服务
- msbuild - 从 Visual Studio 中将参数传递给 msbuild
- underscore.js - 通过使用 underscore.js 传递具有相同属性的两个不同值来验证 json 单个对象
- react-native - 按钮自动点击
- javascript - 已部署网站上背景图像的滚动行为不稳定。它应该是文具,本地构建的预期行为
- stored-procedures - 如何组合查询结果?
- javascript - 本地 xml 被 cors 策略阻止
- java - 如何验证硒中的数组列表WebElement更大和最小值
- mysql - 为什么 CodeIgniter 在我使用 CASE 时会错误地转义查询的某些元素?
- java - 如何使用java将具有相同标题列的两个csv文件合并到另一个csv文件中