pax*_*blo 23
这就是C结构的用途.例如,以下结构是一个元组,它将字符串(最多20个字符长)绑定到整数值:
typedef struct {
char strVal[21];
int intVal;
} tTuple;
Run Code Online (Sandbox Code Playgroud)
类型的变量tTuple(或者如果它们被动态分配则指向它们的指针)可以传递,添加到列表中,并以任何对您的情况有意义的方式进行操作.
使用与上面类似的结构,以下完整程序显示了这一点.它可能会做一些更多的健全性检查(a),但应该没有显示如何做一个元组(这是问题的问题):
#include <stdio.h>
#include <string.h>
static struct { char strVal[21]; int intVal; } tuple[10];
static int tupleCount = 0;
static void listTuples(void) {
printf("==========\nTuple count is %d\n", tupleCount);
for (int i = 0; i < tupleCount; ++i)
printf(" [%s] -> %d\n", tuple[i].strVal, tuple[i].intVal);
puts("==========");
}
static void addTuple(char *str, int val) {
printf("Adding '%s', mapped to %d\n", str, val);
strcpy(tuple[tupleCount].strVal, str);
tuple[tupleCount++].intVal = val;
}
static void deleteTuple(char *str) {
int index = 0;
while (index < tupleCount) {
if (strcmp(str, tuple[index].strVal) == 0) break;
++index;
}
if (index == tupleCount) return;
printf("Deleting '%s', mapped to %d\n", str, tuple[index].intVal);
if (index != tupleCount - 1) {
strcpy(tuple[index].strVal, tuple[tupleCount - 1].strVal);
tuple[index].intVal = tuple[tupleCount - 1].intVal;
}
--tupleCount;
}
int main(void) {
listTuples();
addTuple("aardvark", 31);
addTuple("buffalo", 41);
addTuple("camel", 59);
addTuple("dingo", 27);
listTuples();
deleteTuple("buffalo");
listTuples();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
该计划的输出是:
==========
Tuple count is 0
==========
Adding 'aardvark', mapped to 31
Adding 'buffalo', mapped to 41
Adding 'camel', mapped to 59
Adding 'dingo', mapped to 27
==========
Tuple count is 4
[aardvark] -> 31
[buffalo] -> 41
[camel] -> 59
[dingo] -> 27
==========
Deleting 'buffalo', mapped to 41
==========
Tuple count is 3
[aardvark] -> 31
[dingo] -> 27
[camel] -> 59
==========
Run Code Online (Sandbox Code Playgroud)
(a)例如检查字符串长度和数组计数是否溢出,或禁止重复键(如果需要).