首页 > 解决方案 > 如何取消引用 C 中的多层双重嵌套指针以实现动态堆栈?

问题描述

我正在尝试在 C 中实现一种动态的堆栈。这是代码:

void **x; // global database

void*
pop() {
  void *a = x[1];
  int *b = (int*)(&a[0]);
  int c = *b;
  void *d = ((void**)&a)[c];
  ((int*)&a)[0] = c - 1;
  return d;
}

void
push(void *d) {
  void *a = x[1];
  int *b = (int*)(&a[0]);
  int c = *b + 1;
  ((void**)&a)[c] = d;
  ((int*)&a)[0] = c;
}

void
init() {
  void **a; // this var can be ignored for this question.
  void **b; // this is the one I'm dealing with.

  a = malloc(sizeof(void*) * 100);
  b = malloc(sizeof(void*) * 100);
  x = malloc(sizeof(void*) * 10000);

  a[0] = (0);
  b[0] = (0); // it is a stack, but the first item in the array
  // is the size of the stack.
  // the stack is otherwise of arbitrary elements.

  x[0] = a;
  x[1] = b;
}

int
main(int argc, char **argv) {
  init();
  push(argv);
  char **a = pop();
  puts((char*)(a[0]));
}

我本质上只是想将其推argv入堆栈,然后将其弹出。

然后我想记录其中一个项目(或整个项目,无论哪种方式)。

根据我调整指针的方式,它会记录空白或空值。我怎样才能让它工作?

标签: carrayspointersstackvoid-pointers

解决方案


推荐阅读