-1

I am trying to initialize a struct in its constructor but I run into a compiler error on the last line when I am initializing the member header.length. Is its size known at the time?

This is the compiler error and the structure:

In constructor ‘stDescriptor::stDescriptor()’:
error: expected primary-expression before ‘)’ token


struct stDescriptor {
    usb_functionfs_descs_head   header;
    stDescriptorBody fs_descs;
    stDescriptorBody hs_descs;

    stDescriptor(){
        header.fs_count = 3;
        header.magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC);
        header.hs_count = 3;
            header.length = cpu_to_le32(sizeof stDescriptor);
         }
};
Adrian McCarthy
  • 43,194
  • 15
  • 118
  • 167
tzippy
  • 6,154
  • 24
  • 76
  • 139

1 Answers1

4

You need

header.length = cpu_to_le32(sizeof(stDescriptor));

because stDescriptor is a type name, not an expression.

5.3.3 Sizeof [expr.sizeof]

1 The sizeof operator yields the number of bytes in the object representation of its operand. The operand is either an expression, which is an unevaluated operand (Clause 5), or a parenthesized type-id. [...]

Community
  • 1
  • 1
Luchian Grigore
  • 245,575
  • 61
  • 446
  • 609
  • Question aside: is sizeof(expression) a sizeof expression ? –  Jan 28 '14 at 16:26
  • @DieterLücking if I understand you correctly, yes, this [is a C question](http://stackoverflow.com/questions/18898736/what-does-sizeof-without-do/18898832#18898832) but the logic is the same. – Shafik Yaghmour Jan 28 '14 at 16:35