需要帮助理解指针和各种其他C的东西

nub*_*ela 0 c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct dict_pair {
  void *key;
  void *value;
  struct dict_pair *tail;
} dict;


dict* NewDictionary(void) {
  dict *dictionary = malloc(sizeof(dict)); //or we can malloc(sizeof(struct dict_pair))
  dictionary->tail = NULL;
}

//dict operations
void put(dict *dictionary, void *key, void *value) {
  //new pair
  dict *new_pair = malloc(sizeof(dict));
  new_pair->key = key;
  new_pair->value = value;
  //chaining
  new_pair->tail = NULL;
  dict *last_node = dictionary;
  while (last_node->tail != NULL) {
    last_node = last_node->tail;
  }

  last_node->tail = new_pair;
}

void* get(dict *dictionary, void *key) {
  dict *current_dict = dictionary;
  while (1) {
    if (current_dict->key == key) {
      return current_dict->value;
    }
    else if (dictionary->tail != NULL) {
      current_dict = current_dict->tail;
    } else break;
  }
  return NULL;
}
//end operations

int main(void) {
  dict *dictionary = NewDictionary();
  put(dictionary,(void *) "buffer1",(void *) "Fake1");
  put(dictionary,(void *) "buffer2",(void *) "Fake2");
  put(dictionary,(void *) "key",(void *) "This is the value.");
  char *result = (char *) get(dictionary, (void *) "key");
  printf("%s\n",result);
}
Run Code Online (Sandbox Code Playgroud)

所以我设法编写上面的代码来实现字典.虽然我能够编写代码并编译并使其工作到期望,但有一些我不清楚的东西.主要是关于指针:

dict *current_dict = dictionary;
Run Code Online (Sandbox Code Playgroud)

让我们以此行为例.我们声明一个包含dict类型的变量.current_dict是一个指针,对吧?和字典是一个指针.但是,*current_dict不是指针,它如何分配给指针?

或者我是否必须明确键入此以使其出错?

dict (*current_dict) = dictionary;
Run Code Online (Sandbox Code Playgroud)

如果是这样,这是否意味着上面的行意味着我们用dict类型声明一个current_dict变量,它是一个指针.不是那个宣言

(dict*) current_dict = dictionary;
Run Code Online (Sandbox Code Playgroud)

如您所见,间距和位置让我感到困惑.

有人可以帮助解释*定位的差异吗?

谢谢!

Art*_*ius 7

虽然dict *dictionarydict* dictionary在C相同的含义,我更喜欢前者.

我更喜欢用这些术语来思考指针声明:

int   x; //  x is an int
int  *y; // *y is an int
int **z; //**z is an int
Run Code Online (Sandbox Code Playgroud)

如果你记得那是指*y向的对象y,那么它y必须是一个指向int的指针.同样z必须是一个指针到指针的指针.