sizeof single struct member in C

2020-01-27 09:18发布

I am trying to declare a struct that is dependent upon another struct. I want to use sizeof to be safe/pedantic.

typedef struct _parent
{
  float calc ;
  char text[255] ;
  int used ;
} parent_t ;

Now I want to declare a struct child_t that has the same size as parent_t.text.

How can I do this? (Pseudo-code below.)

typedef struct _child
{
  char flag ;
  char text[sizeof(parent_t.text)] ;
  int used ;
} child_t ;

I tried a few different ways with parent_t and struct _parent, but my compiler will not accept.

As a trick, this seems to work:

parent_t* dummy ;
typedef struct _child
{
  char flag ;
  char text[sizeof(dummy->text)] ;
  int used ;
} child_t ;

Is it possible to declare child_t without the use of dummy?

标签: c struct sizeof
9条回答
Ridiculous、
2楼-- · 2020-01-27 10:08

You can use a preprocessor directive for size as:

#define TEXT_MAX_SIZE 255

and use it in both parent and child.

查看更多
何必那么认真
3楼-- · 2020-01-27 10:15

c++ solution:

sizeof(Type::member) seems to be working as well:

struct Parent
{
    float calc;
    char text[255];
    int used;
};

struct Child
{
    char flag;
    char text[sizeof(Parent::text)];
    int used;
};
查看更多
家丑人穷心不美
4楼-- · 2020-01-27 10:16

struct.h has them already defined,

#define fldsiz(name, field) \
    (sizeof(((struct name *)0)->field))

so you could,

#include <stdlib.h> /* EXIT_SUCCESS */
#include <stdio.h>  /* printf */
#include <struct.h> /* fldsiz */

struct Penguin {
    char name[128];
    struct Penguin *child[16];
};
static const int name_size  = fldsiz(Penguin, name) / sizeof(char);
static const int child_size = fldsiz(Penguin, child) / sizeof(struct Penguin *);

int main(void) {
    printf("Penguin.name is %d chars and Penguin.child is %d Penguin *.\n",
           name_size, child_size);
    return EXIT_SUCCESS;
}

but, on looking in the header, it appears that this is a BSD thing and not ANSI or POSIX standard. I tried it on a Linux machine and it didn't work; limited usefulness.

查看更多
登录 后发表回答