gpt4 book ai didi

c - 如何创建静态常量数组的数组

转载 作者:行者123 更新时间:2023-11-30 15:12:28 26 4
gpt4 key购买 nike

在我的 .c 文件中,我有 jpg[4] 来检查某些文件中的 jpg 签名(使用 memcmp()):

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

比较效果很好,现在我想添加一些更多的格式签名,例如:

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

我不想复制具有不同签名变量的粘贴代码。如何创建此类不更改值的数组并使用for(;;)迭代每个签名。我不想在方法内声明它们。

我知道这是一些基本的东西,但我对 C 还很陌生,所以对我来说不是那么明显。

伪代码:

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
}
}

最佳答案

也许你想要这样的东西:

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 };

现在您可以迭代 signantures 数组。但是您不知道 signatures 数组中每个签名的长度。

您可以通过对每个签名的第一个元素的长度进行编码来解决此问题:

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
}
}

关于c - 如何创建静态常量数组的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35065218/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com