2

Here's what I'm trying to do:

myValueType function1(myParam){}

myValueType function2(myParam){}

myArray[CONSTANT_STATE1] = &function1;
myArray[CONSTANT_STATE2] = &function2;

myValue = (*myArray[CONSTANT_STATE1])(myParam);

When I compile, it throws an error that I've redeclared function1.

What's the best way to do this?

4

2 回答 2

3

根据用户Vijay Mathew的这个 SO 回答

The C Programming Language的6.6 节介绍了一个简单的字典(哈希表)数据结构。我认为没有比这更简单的字典实现了。为了您的方便,我在这里复制代码。

struct nlist { /* table entry: */
    struct nlist *next; /* next entry in chain */
    char *name; /* defined name */
    char *defn; /* replacement text */
};

#define HASHSIZE 101
static struct nlist *hashtab[HASHSIZE]; /* pointer table */

/* hash: form hash value for string s */
unsigned hash(char *s)
{
    unsigned hashval;
    for (hashval = 0; *s != ’\0’; s++)
      hashval = *s + 31 * hashval;
    return hashval % HASHSIZE;
}

/* lookup: look for s in hashtab */
struct nlist *lookup(char *s)
{
    struct nlist *np;
    for (np = hashtab[hash(s)]; np != NULL; np = np->next)
        if (strcmp(s, np->name) == 0)
          return np; /* found */
    return NULL; /* not found */
}

char *strdup(char *);
/* install: put (name, defn) in hashtab */
struct nlist *install(char *name, char *defn)
{
    struct nlist *np;
    unsigned hashval;
    if ((np = lookup(name)) == NULL) { /* not found */
        np = (struct nlist *) malloc(sizeof(*np));
        if (np == NULL || (np->name = strdup(name)) == NULL)
          return NULL;
        hashval = hash(name);
        np->next = hashtab[hashval];
        hashtab[hashval] = np;
    } else /* already there */
        free((void *) np->defn); /*free previous defn */
    if ((np->defn = strdup(defn)) == NULL)
       return NULL;
    return np;
}

char *strdup(char *s) /* make a duplicate of s */
{
    char *p;
    p = (char *) malloc(strlen(s)+1); /* +1 for ’\0’ */
    if (p != NULL)
       strcpy(p, s);
    return p;
}

请注意,如果两个字符串的哈希值发生冲突,可能会导致O(n)查找时间。您可以通过增加 的值来减少可能发生的碰撞HASHSIZE。有关数据结构的完整讨论,请参阅本书。

于 2013-11-01T02:44:47.847 回答
1

您显示的代码几乎是正确的。问题出在您的函数声明中:

myValueType function1(myParam){}

myValueType function2(myParam){}

这些是旧式 K&R 非原型声明 - 参数的名称是myParam,并且类型尚未指定。也许你是这个意思?

myValueType function1(myParamType myParam){}

myValueType function2(myParamType myParam){}

将您的代码扩展为一个最小的可编译示例:

typedef int myValueType, myParamType;
enum { CONSTANT_STATE1, CONSTANT_STATE2 };

myValueType function1(myParamType myParam){}

myValueType function2(myParamType myParam){}

void f(myParamType myParam)
{
    myValueType myValue;
    myValueType (*myArray[2])(myParamType);

    myArray[CONSTANT_STATE1] = &function1;
    myArray[CONSTANT_STATE2] = &function2;

    myValue = (*myArray[CONSTANT_STATE1])(myParam);
}
于 2013-11-01T03:01:11.950 回答