私は C とその難解な隠された力についてもっと学ぼうとしており、配列として使用することを意図した、void へのポインターを含むサンプル構造体を作成しようとしました。編集: 重要な注意: これは生の C コード用です。
この構造体があるとしましょう。
typedef struct mystruct {
unsigned char foo;
unsigned int max;
enum data_t type;
void* data;
} mystruct;
データにunsigned char、unsigned short int、unsigned long int のいずれかの最大値を保持させたい場合、data_t 列挙にはこれら 3 つのケースの値が含まれます。
enum Grid_t {gi8, gi16, gi32}; //For 8, 16 and 32 bit uints.
次に、この構造体の 1 つを初期化して割り当てるこの関数があり、新しい構造体へのポインターを返すことになっています。
mystruct* new(unsigned char foo, unsigned int bar, long value) {
mystruct* new;
new = malloc(sizeof(mystruct)); //Allocate space for the struct.
assert(new != NULL);
new->foo = foo;
new->max = bar;
int i;
switch(type){
case gi8: default:
new->data = (unsigned char *)calloc(new->max, sizeof(unsigned char));
assert(new->data != NULL);
for(i = 0; i < new->max; i++){
*((unsigned char*)new->data + i) = (unsigned char)value;
//Can I do anything with the format new->data[n]? I can't seem
//to use the [] shortcut to point to members in this case!
}
break;
}
return new;
}
コンパイラは警告を返しませんが、この方法についてはよくわかりません。ポインターを使用する正当な方法ですか?
より良い方法©はありますか?
呼び損ねました。mystruct* P; のように P = 新しい (0,50,1024);
ユニオンは興味深いですが、私が望んでいたものではありません。とにかく、特定のケースごとに個別にアプローチする必要があるため、キャストはユニオンと同じくらい良いようです。特に、32 ビット配列よりもはるかに大きな 8 ビット配列が必要だったので、共用体は役に立たないようです。そのために、私はそれを単にlongの配列にします:P