c - 将 void 分配给双指针

标签 c void

我需要理解为什么将 void* 分配给 int** 会起作用,但是当打印 int** 的值时,它不管用。这是代码:

int k = 3;
int *l = &k;
void *a = l; 
int **c = a; // if I assign, &a, the below line work, but get warning: incompatible
             // pointer type.
printf("%d", **c); // Code break;

但是这一行

printf("%d", *c); // will work, but get warning "%d expect int but of type int *".

更新:我在 OOC book 中看到了这种类型的代码,作者是这样做的:

struct Class {
   size_t size;
   int (*differ)(const void *self, const void *b);
   ..... Some more code ....

};

int differ(const void *self, const void *b) {
  // Note this line
  const struct Class **cp = self;
  assert(self && *cp && (*cp)->differ);
  return (*cp)->differ(self, b);
}

最佳答案

你有这种情况:

+---+
| l | --\
+---+    \     +---+
          >--> | k |
+---+    /     +---+
| a | --/
+---+

I.e. both l and a points directly to k.

When you then do

int **c = a;

你让 c 指向 a 指向的内容(即它与 int **c = &k 相同) ,但是您将 c 声明为指向 int 的指针,但使其直接指向 int。这意味着使用单解引用 (*c) 你会得到 k 的值,当你使用双解引用 (**c) 时你使用 k 的值作为指针(它不是)。

我假设您真正想要的是这种情况:

+---+     +---+     +---+
| a | --> | l | --> | k |
+---+     +---+     +---+

which you will get by doing

void *a = &l;

然后使用 c 作为指向指针的指针将起作用,因为 a 是指向指针的指针。


如果你继续第一个场景,你有

int   k;
int  *l = &k;
void *a = l;

然后做

int **c = (int **) &a;  // The typecast is needed

那么你有以下情况:

          +---+
          | l | --\
          +---+    \     +---+
                    >--> | k |
+---+     +---+    /     +---+
| c | --> | a | --/
+---+     +---+

这会起作用,因为 c 实际上是 指向某物的指针。

关于c - 将 void 分配给双指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23558615/

相关文章:

c - 运行 malloc 后内存损坏

c - void * 赋值给 void **

c - 如何显示从文件中读取的分数

c++ - 数组内的自增运算符

c++ - 在 C++ 中使用函数(void、double、int)

c - printf ("%p") 并转换为 (void *)

c++ - struct int数据类型不适用于关系运算符

c++ - 'void' 之前的预期不合格 ID

c - 'sizeof (function name)' 返回什么?

c++ - .net 应用程序的 Bootstrap (预安装程序)