0

I have this helper function that I like to define so it looks like for one specific function

int change_int_val(unsigned int * from,unsigned int *to)
{
    *to=*from;
    return 0;
}

So actually it assign the from to to now the problem is I want to pass all fields that I have in my struct so assume I have struct iphdr from networking and I want to assign value 5 to ihl which is 4 bit size defined as unsigned int ihl:4; now if I call the above function like this

 change_int_val((unsigned int *)5,(unsigned int *)(&ip->ihl));

I get error that

tcp_work.c:45:59: error: cannot take address of bit-field ‘ihl’
   45 |         change_int_val((unsigned int *)5,(unsigned int *)(&ip->ihl));

So can I make this helper function like the one above and escape this limitation that pointer size 1 byte issue with fields that are less than 1 byte in my case as I like to pass the address of iphdr->ihl to my helper function change_int_val

halfer
  • 19,824
  • 17
  • 99
  • 186
user786
  • 3,902
  • 4
  • 40
  • 72
  • like to pass the address of ->ihl to the helper function – user786 Dec 23 '21 at 06:31
  • 1
    `(unsigned int *)5` only makes sense on smaller embedded systems where you need a pointer to the actual memory at address `5`. Not anywhere else. – Some programmer dude Dec 23 '21 at 06:31
  • 2
    Also, the smallest addressable unit on any CPU the last 40-50 years or so is the *byte*. You can't have pointers to individual bits. – Some programmer dude Dec 23 '21 at 06:32
  • Oh and please don't forget how to create a *[mre]* to show us. While we can deduce some information, having the bitfield structure itself doesn't hurt. – Some programmer dude Dec 23 '21 at 06:33
  • 4
    Lastly, what is wrong with plain assignments? Like `ip->ihl = 5` (which is what I assume you want to do)? – Some programmer dude Dec 23 '21 at 06:34
  • 1
    If I understand you want to manipulate `struct iphdr` within the function, why not pass `struct iphdr *` as one of the parameters and then change the value of the bitfield directly within the function? – David C. Rankin Dec 23 '21 at 06:42
  • @DavidC.Rankin ok also can u tell why fields that are less than 1 byte are normally don't need ntohs byte order function or or ntohl kind of conversion but bigger fields sized more than 1 byte needs byte order conversion for example ihl and protocol dont need ntohs conversion – user786 Dec 23 '21 at 06:55
  • There is a good question discussing bitfields at [When to use bit-fields in C?](https://stackoverflow.com/questions/24933242/when-to-use-bit-fields-in-c) and see the answer to [C/C++ Is bitfield endianess really a problem in actual practice?](https://stackoverflow.com/a/57081370/3422102) (discussing `struct iphdr`) – David C. Rankin Dec 23 '21 at 07:09
  • Regarding `ntohs` and similar, it's for *byte* ordering of *multi-byte* values (like 16- or 32-bit values). – Some programmer dude Dec 23 '21 at 08:58

0 Answers0