ここでは、静的に割り当てられた2つ以上のアレイを連結するためのソリューションを示します。静的に割り当てられた配列は、コンパイル時に長さが定義される配列です。演算子は、これらの配列のsizeof
サイズ(バイト単位)を返します。
char Static[16]; // A statically allocated array
int n = sizeof(Static_array); // n1 == 16
演算子を使用して、 2つ以上の配列を連結し、場合によっては配列の全長を返すsizeof
マクロのセットを作成できます。
私たちのマクロ:
#include <string.h>
#define cat(z, a) *((uint8_t *)memcpy(&(z), &(a), sizeof(a)) + sizeof(a))
#define cat1(z, a) cat((z),(a))
#define cat2(z, a, b) cat1(cat((z),(a)),b)
#define cat3(z, a, b...) cat2(cat((z),(a)),b)
#define cat4(z, a, b...) cat3(cat((z),(a)),b)
#define cat5(z, a, b...) cat4(cat((z),(a)),b)
// ... add more as necessary
#define catn(n, z, a ...) (&cat ## n((z), a) - (uint8_t *)&(z)) // Returns total length
使用例:
char One[1] = { 0x11 };
char Two[2] = { 0x22, 0x22 };
char Three[3] = { 0x33, 0x33, 0x33 };
char Four[4] = { 0x44, 0x44, 0x44, 0x44 };
char All[10];
unsigned nAll = catn(4, All, One, Two, Three, Four);
ただし、マクロを定義した方法のおかげで、サイズを返す限り、任意のタイプのオブジェクトを連結できます。sizeof
例えば:
char One = 0x11; // A byte
char Two[2] = { 0x22, 0x22 }; // An array of two byte
char Three[] = "33"; // A string ! 3rd byte = '\x00'
struct {
char a[2];
short b;
} Four = { .a = { 0x44, 0x44}, .b = 0x4444 }; // A structure
void * Eight = &One; // A 64-bit pointer
char All[18];
unsigned nAll = catn(5, All, One, Two, Three, Four, Eight);
定数リテラルを使用すると、これらのマクロを使用して、定数、関数の結果、さらには定数配列を連結することもできます。
// Here we concatenate a constant, a function result, and a constant array
cat2(All,(char){0x11},(unsigned){some_fct()},((uint8_t[4]){1,2,3,4}));