通过宏创建数组

时间:2014-03-14 17:48:05

标签: c

我有学校作业,差不多完成了,但我注意到规范中的一些细节,我不知道该怎么做。

规范如下: 为位数组定义这些宏:

BitArray(arrayname,size)

//定义并取消位字段。你必须使它本地/自动。 (不确定翻译是否正确,我无法找到很多关于"自动"字段...)我理解它,因为我必须像这样制作宏(我不能这样做)使用动态内存(malloc)):

#define BitArray(arrayname,size) unsigned long bits[size+some operations]

typedef BitArray_t

我的问题就出现了,因为我们必须使用新类型,它在所有其他函数中用于传递位数组。我不知道如何在头文件中定义它。当我这样的时候:

Headerfile.h
typedef unsigned long *bits; // 

//We also have to storage size of the bit array. So I can either put it in 0th array element, or make struct (there came even more problems)

#define SetBit(array, index, value)\
{\
     ...\
     1 << position & array[2];\ // PROBLEM
     ...\
}

这里有问题。它告诉我我比较两种不同的类型。如果我把*数组,它当然有效,但我没有 想要创建指针数组,我相信我只是做错了什么。是否可以制作我的typedef数组,而不必每次都遵守它?我不确定我是否写得很清楚,但我希望你至少能理解我一点。

1 个答案:

答案 0 :(得分:0)

我会为位数组

使用结构
typedef struct {
    unsigned int size,
    unsigned long bits[];
} BitArray_t;

我在堆栈上初始化它的方式如下

#define BITS_PER_BYTE 8

unsigned int size = 1024;

/* add 1 here in case the size is not evenly divisible by number of bits 
   in unsigned long */
unsigned int bit_arr_size = (size / sizeof(unsigned long) / BITS_PER_BYTE) + 1;

unsigned int bits[bit_arr_size] = {0}; /* this initializes the entire array */

/* Name of the struct is going to be a_bitarray */
/* struct initialization */
BitArray_t a_bitarray = { .size = bit_arr_size, .bits = bits };

将其转换为宏

#define BitArray(arrayname, size) \
unsigned int bit_arr_size = ((size) / sizeof(unsigned long) / 8) + 1; \
unsigned int bits[bit_arr_size] = {0}; /* this initializes the entire array */ \
BitArray_t arrayname = { .size = bit_arr_size, .bits = bits };