[英]Is it OK to use bitfields in dynamically allocated structure in C?
I'm going to implement a singly linked list program with bitfield in its structure, something like this: 我将用结构的位域实现一个单链列表程序,如下所示:
typedef struct large
{
unsigned number :4;
struct large *next;
} large;
int main()
{
large *g;
g=(large *)malloc(sizeof(large));
g->number=15;
printf("%d",g->number);
return 0;
}
The above program is working correctly but I read in GeeksForGeeks that, 上面的程序正常运行,但是我在GeeksForGeeks中读到,
We cannot have pointers to bit field members as they may not start at a byte boundary.
我们不能有指向位字段成员的指针,因为它们可能不是从字节边界开始的。
Will there be problems if I code it further for linked list implementation? 如果为链接列表实现进一步编码会不会有问题?
The pointer g
in your program is a pointer to a structure variable to which you allocated memory dynamically. 程序中的指针
g
是指向动态分配内存的结构变量的指针。
g->number
is not the address of the member number
but its value. g->number
不是成员number
的地址,而是其值。
You cannot have a pointer like 你不能有这样的指针
unsigned char *ptr=&(g->number);
you should get an error like cannot take address of bit-field
你应该得到一个错误,例如
cannot take address of bit-field
malloc-ing any structures including those containing bitfields is absolutely OK 绝对分配任何结构,包括那些包含位域的结构
We cannot have pointers to bit field members as they may not start at a byte boundary.
But you do not get the address of the bitfield - only for the structure itself and its size and location is always a multiple of byte. 但是您不会获得位域的地址-仅针对结构本身,并且其大小和位置始终是字节的倍数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.