-2

I want to print a_size in header struct like "a_size = 3" but, it prints "a_size = 1".

How to get the value a_size?

#include <stdio.h>

struct header {
   unsigned int total_size : 6;
   unsigned int a_size : 3;
   unsigned int b_size : 2;
   unsigned int c_size : 3;
   unsigned int d_size : 2;
};

int main() {
   struct header h;
   printf("\n=========== HEADER ===========\n");
   printf("a_size : %d\n", h.a_size);

   return 0;
}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
taranndus
  • 29
  • 2
  • 3
    `h.a_size` has never been initialized, it's value is undetermined. But why do you expect `a_size = 3` ? Maybe you should read about bit fields, and/or read this: https://stackoverflow.com/questions/24933242/when-to-use-bit-fields-in-c – Jabberwocky Feb 03 '22 at 10:53
  • 1
    Just to be sure what the real issue in your code is, please tell us in your own words what you think `a_size : 3;` does. – Jabberwocky Feb 03 '22 at 11:05
  • Duplicate of https://stackoverflow.com/questions/3319717/is-there-a-bit-equivalent-of-sizeof-in-c – user3386109 Feb 03 '22 at 11:43
  • @user3386109 not sure if it's a dupe, the question is somewhat unclear. – Jabberwocky Feb 03 '22 at 11:48
  • @Jabberwocky Seems clear to me. The title states that the OP wants to know the size, and the size given as the expected output matches the size of the bit field in the code. What else do you need? – user3386109 Feb 03 '22 at 11:53
  • @user3386109 yes, but in the question we have: _"How to get the value `a_size`"_. He might think that `int a_size : 3` means: "initialize `a_size` with 3", as he expects `a_size` to be 3. Not the first time the title says something different than the question. – Jabberwocky Feb 03 '22 at 11:56

1 Answers1

1

How to get the value a_size?

First thing first, bit-field is used to limit memory usage, by limiting sizeof() of a data type. So, the value of bit-field like unsigned int a_size : 3; is not printed as 3, instead you have assigned a_size bit-width to 3.

If you want to print 3 then you have to assign a_size to 3 instead of defining it's bit-field as 3.

So, first we have initialize it by using some functions which is written below:

#include <stdio.h>
#include <stdbool.h>

struct header {
   unsigned int total_size : 6;
   unsigned int a_size : 3;
   unsigned int b_size : 2;
   unsigned int c_size : 3;
   unsigned int d_size : 2;
};

/*
  This function inits the `struct header`.
  @param h reference of your variable
  @returns false if `h` was NULL, otherwise returns true
*/
int init(struct header *h)
{
        if(!h)
            return false;
        h->a_size = 3;
        h->b_size = 2;
        h->c_size = 3;
        h->d_size = 2;
        h->total_size = 6;
        return true;
}

int main(void) {
   struct header h;
   init(&h);
   printf("\n=========== HEADER ===========\n");
   printf("a_size : %d\n", h.a_size);

   return 0;
}
Darth-CodeX
  • 2,166
  • 1
  • 6
  • 23