Dancia
Dancia

Reputation: 812

How to create array of static const arrays

In my .c file I had jpg[4] to check for jpg signature (using memcmp()) in certain file:

static const unsigned __int8 jpg[4] = { 0xFF, 0xD8, 0xFF, 0xDB };

Comparison works great and now I would like to add some more format signatures, for example:

static const unsigned __int8 png[8] = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A };

I dont want to copy paste code with different signature variable. How do I create an array of such not changing values and iterate through each signature using for(;;). I don't want to declare them inside methods.

I know it's some basic stuff, but I'm pretty new to C, so it's not so obvious to me.

In pseudo code:

bool isImg(bool * value)
{
for(int index = 0; index < signatures count; i+++) <-- for should iterate through signatures
    {
        // use signature[index] which is array of bytes { 0xFF, Ox... }
        // check signature
    }
}

Upvotes: 0

Views: 87

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50775

Maybe you want something like this:

static const unsigned __int8 jpg[4] = { 0xFF, 0xD8, 0xFF, 0xDB };
static const unsigned __int8 png[8] = { 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A };

static const unsigned __int8 *signatures[] = { jpg, png };

Now you can iterate through the sigantures array. But then you don't know the length of each signature in the signatures array.

You could get around this by encoding the length in the first element of each signature:

static const unsigned __int8 jpg[] = { 4, 0xFF, 0xD8, 0xFF, 0xDB };
static const unsigned __int8 png[] = { 8, 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A };

static const unsigned __int8 *signatures[] = { jpg, png };

bool isImg(bool * value)
{
  for(int i = 0; i < (sizeof (signatures)) / (sizeof (__int8*)); i++)
  {
    const unsigned __int8 *signature = signatures[i];
    int signaturesize = signature[0]; // here: 4 for i==0, 8 for i==1

        // use signature[i] which is array of bytes { 0xFF, Ox... }
        // check signature
  }
}

Upvotes: 1

Related Questions