gpt4 book ai didi

我可以使用标签作为 C 全局数据表中的索引吗?

转载 作者:太空宇宙 更新时间:2023-11-04 08:31:10 24 4
gpt4 key购买 nike

我有一个很大的全局数组,我在其中不断更改一些值,这些值在为不同目的编译时需要更改表。基本上,表格是一个核心结构,根据不同的目的,可能会添加/删除附加值。这些值有点像:

int global_array[] = 
{
...
6, 6, 78, 9,
12,
13,5
19,
47, 768, 98, 89
...
};

我需要访问这些表中的一些核心结构值(这里假设为“12”)。因此,在为不同目的进行编译时,相关值(“12”)的索引会发生变化。出于同样的原因,我不能将此表保留为结构。请记住,这是一个巨大的表格,出于某种原因,我们不会以统一的方式写入值(线性读取)。

因此,对于每个新用途,我都必须手动计算值“12”的索引,这很乏味。我想要一个面向 future 的流程。

我想知道我是否可以使用类似的东西:

int global_array[] = 
{
...
6, 6, 78, 9,
INDEX: 12,
13,5
19,
47, 768, 98, 89
...
};

并在运行时访问/修改值,如下所示:

*(uint8 *)INDEX = 20;

最佳答案

您可以在指向特定条目的那个点周围保留额外的指针变量。需要时,您可以调整指针指向的数组条目。

例子:

#include <stdio.h>

int global[] = {1,2,3,4,5,6,7};
int *idx = &global[0];

int main() {
*idx = 20;
printf("%d\n", *idx);
return 0;
}

或者,您可以使用预处理器宏(如果引用的位置在编译时已知并且不会更改):

#include <stdio.h>

int global[] = {1,2,3,4,5,6,7};
#define INDEX (global[0])

int main() {
INDEX = 20;
printf("%d\n", INDEX);
return 0;
}

鉴于您只需要在程序启动时执行一次此操作,也许您只需要一个为您计数的函数。

例子:

#include <stdio.h>

int global[] = {1,2,3,4,5,6,7};

int find_index(int value, int *array, size_t size) {
for (int i = 0; i < size; i++)
if (array[i] == value)
return i;
return -1;
}

int main() {
int value = 4;
int index = find_index(value, global, sizeof(global)/sizeof(*global));
printf("index of %d: %d\n", value, index);
return 0;
}

这是输出:

$ gcc tt.c -std=c99 && ./a.out
index of 4: 3

如果需要在应用程序的整个运行期间跟踪大量条目的位置,您应该考虑使用键值存储(例如,二叉搜索树)来跟踪值的索引。然后,您应该使用封装更新和检索操作的特殊方法,这些操作还将调整存储在该“索引”数据结构中的索引。

关于我可以使用标签作为 C 全局数据表中的索引吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28274643/

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