首页 > 解决方案 > 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?

标签: cfunctionstructure

解决方案


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

#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.


推荐阅读