0

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?

damadam
  • 330
  • 4
  • 17

1 Answers1

0

Yes, there is a way. You posted very little code, but probably you are searching for smth called offsetof or 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); 
}

See what i did there? I took the offset between struct vidinfo_s and it's member called sVid. Then i subtracted the offset from pVid pointer (which should point inside a struct vidinfo_s structure), thus i was left with the pointer to struct vidinfo_s.

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
  • i'm not really familiar with 'const' cast, are they really useful? – damadam May 24 '18 at 11:52
  • Const lvalues cannot be modified or assigned (that's all). Const variables are not constant expressions. Const does not mean, that you cannot modify the variable, only that you cannot modify it via this handle (you can cast const away and modify it). I use const mostly as cosmetics - to inform others, that i won't change this variable. Maybe in this short example they are more misleading then helpful. Also the const in the pointer was in the wrong place... edited. – KamilCuk May 24 '18 at 12:11