如何创建可变大小的位字段数组?
下面的代码是我尝试的,但没有成功。

#include <stdio.h>
int main()
{
    int n=4;
    struct bite{
        unsigned a1:2;
        unsigned a2:2;
            :
            :
        unsigned a(n-1):2;
        unsigned a(n):2;
    }bits;

    for(i=1;i<=n;i++)
        bits.a[i]=i;

    for(i=1;i<=n;i++)
        printf("%d ",bits.a[i]);

    return 0;
}

最佳答案

无法在运行时定义struct的成员。
您可以使用char数组和一些宏来模拟位数组。

#define BitArray(array, bits) \
  unsigned char array[bits / 8 + 1]

#define SetBit(array, n) \
  do { array[n / 8] |= (1 << (n % 8)) } while (0)
#define GetBit(array, n) \
  ((array[n / 8] >> (n % 8)) & 1)

int main(void)
{
  BitArray(bits, 42); /* Define 42 bits and init to all 0s
                               (in fact this allocates memory for (42/8 + 1) * 8 bits). */

  SetBit(bits, 2); /* Set bit 2. */
  int bit2 = GetBit(bits, 2); /* Get bit 2 */

  ...

类似的2位单词是根据您的代码编写的:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define Define2BitWordArray(array, two_bit_words) \
  unsigned char array[two_bit_words / 4 + 1]

#define Set2BitWord(array, n, value) \
  do { array[n / 4] |= (unsigned char)((value & 0x11) << (2 * (n % 4))); } while (0)
#define Get2BitWord(array, n) \
  ((array[n / 4] >> (2 * (n % 4))) & 0x11)

int main(void)
{
  size_t n = 10;
  Define2BitWordArray(bits, n); /* Define 10 two-bits words
                                  (in fact this allocates memory
                                  for (10/4 + 1) * 4 two-bit bits). */
  memset(bits, 0, sizeof bits); /* Set all bits to 0. */

  for(size_t i = 0; i < n; i++) /* C array's indexes are 0-based. */
  {
    Set2BitWord(bits, i, i);
  }

  for(size_t i = 0; i < n; i++)
  {
    printf("%d ", Get2BitWord(bits, i));
  }
}

关于c - C中的位域结构数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46141169/

10-17 02:43