简体   繁体   中英

dereferencing ‘void *’ pointer in C

So I have those in a .h

stable.h

// The symbol table.
typedef struct stable_s *SymbolTable;

// Data stored.
typedef union {
  int i;
  char *str;
  void *p;
} EntryData;

// Return struct for stable_insert.
typedef struct {
  int new;  // Was a new entry created?
  EntryData *data;  // Data associated with entry.
} InsertionResult;

etc

Then in my .c

stable.c

etc

typedef struct {
    char *key;
    EntryData data;
} Entry;

struct stable_s { /* Indice hash */
    char index;
    int size;
    void *pointer;
};

etc

EntryData *stable_find(SymbolTable table, const char *key){
    int k;
    char c;

    if (key[0] >= 'A' && key[0] <= 'Z')
        c = table[(key[0] - 65)].index;
    else if (key[0] >= 'a' && key[0] <= 'z')
        c = table[(key[0] - 141)].index;
    else
        c = table[26].index;

    c -= 65;

    if (table[c].size == 0)
        return NULL;

    k = busca_binaria(table[c].pointer, table[c].size, key);
    if (strcmp(table[c]->pointer[k]->key, key) == 0)
        return table[c]->pointer[k]->data;

    return NULL;
}

And gcc -std=c99 stable.c -o stable is giving me those errors:

 stable2.c: In function 'stable_find': stable2.c:128:24: error: invalid type argument of '->' (have 'struct stable_s') if (strcmp(table[c]->pointer[k]->key, key) == 0) stable2.c:129:24: error: invalid type argument of '->' (have 'struct stable_s') return table[c]->pointer[k]->data; 

What am I missing? I'm really lost in the syntax.

Let us look at these lines:

k = busca_binaria(table[c].pointer, table[c].size, key);
if (strcmp(table[c]->pointer[k]->key, key) == 0)
    return table[c]->pointer[k]->data;

What is table ? It is struct stable_s *

So

table[c]

is a struct stable_s - and it is not a pointer.

So back to the lines:

k = busca_binaria(table[c].pointer, table[c].size, key);
                  ^^^^^^^^^^^^^^^^
                  Correct as table[c] is a struct stable_s

if (strcmp(table[c]->pointer[k]->key, key) == 0)
           ^^^^^^^^^^^^^^^^^^^^
           Wrong as table[c] is not a point

    return table[c]->pointer[k]->data;
           ^^^^^^^^^^^^^^^^^^^^
           Wrong as table[c] is not a point

There seems to be other problems in your code (like dereferencing `void*) but the above should relate to the compiler errors.

Maybe this line:

if (strcmp(table[c]->pointer[k]->key, key) == 0)

should be:

if (strcmp(((Entry*)table[c].pointer)[k].key, key) == 0)

but I can't be sure as you haven't posted code that tells this.

And maybe this line:

return table[c]->pointer[k]->data;

should be:

return &(((Entry*)table[c].pointer)[k].data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM