写一个C语言查表函数
时间: 2023-02-06 13:11:18 浏览: 130
好的,这是一个 C 语言的查表函数的例子:
```
#include <stdio.h>
#define TABLE_SIZE 10
/* 定义表项结构体 */
struct TableEntry {
int key;
char value[100];
};
/* 定义表结构体 */
struct Table {
struct TableEntry entries[TABLE_SIZE];
};
/* 初始化表 */
void init_table(struct Table *table) {
for (int i = 0; i < TABLE_SIZE; i++) {
table->entries[i].key = -1;
table->entries[i].value[0] = '\0';
}
}
/* 插入表项 */
void insert_entry(struct Table *table, int key, char *value) {
for (int i = 0; i < TABLE_SIZE; i++) {
if (table->entries[i].key == -1) {
table->entries[i].key = key;
strcpy(table->entries[i].value, value);
return;
}
}
printf("Error: table is full\n");
}
/* 查找表项 */
char *lookup_entry(struct Table *table, int key) {
for (int i = 0; i < TABLE_SIZE; i++) {
if (table->entries[i].key == key) {
return table->entries[i].value;
}
}
return NULL;
}
int main() {
struct Table table;
init_table(&table);
insert_entry(&table, 1, "apple");
insert_entry(&table, 2, "banana");
insert_entry(&table, 3, "cherry");
printf("%s\n", lookup_entry(&table, 2));
printf("%s\n", lookup_entry(&table, 3));
printf("%s\n", lookup_entry(&table, 4));
return 0;
}
```
这个例子定义了一个表结构体 `struct Table`,其中包含了一个表项数组 `struct TableEntry entries[TABLE_SIZE]`。表项结构体 `struct TableEntry` 包含了一个整型键 `key` 和一个字符数组值 `value`。
然后我们定义了三个函数:
- `init_table` 函数用于初始化表,将表中所有表项的键设置为 -1,
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)