如何在C中没有结构的情况下嵌套双指针? [英] How to have nested double pointers without structs in C?

查看:61
本文介绍了如何在C中没有结构的情况下嵌套双指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里我有以下代码:

void **x;

void
push(void * value) {
  void *a = x[1];
  int *b = (int*)(&a[0]);
  printf("%d\n", *b);
  (((void*)&a))[*b + 1] = *value;
}

void
init() {
  void **a;
  void **b;

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

  a[0] = (0);
  b[0] = (0);

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

int
main(int argc, char **argv) {
  init();
  push(argv);
  x[3] = "e";
  x[4] = "e";
  puts(x[4]);
}

本质上,我的目标是拥有一个任意大小的数组x,其中可以包含任意嵌套元素.然后我想把 init 中的 a 也当作一个双空指针,这样它也可以有任何东西.我打算简单地使它成为一个动态大小的整数数组.然后 b 我想包含固定数量的任意元素.

Essentially, my goal is to have an arbitrarily-sized array x which can contain arbitrary nested elements. Then I want to treat a in init as also a double void pointer so it too can have anything. I plan on simply making it a dynamically sized array of integers. Then b I want to contain a fixed number of arbitrary elements.

然而,我已经尝试了几十种指针和引用的组合,目前只是通过反复试验.在最新配置之一上获得此功能.

However, I have tried dozens of combinations of pointers and references and am at this point simply going by trial and error. Getting this on one of the latest configurations.

$ make test
test/test.c:19:25: error: incomplete type 'void' is not assignable
  (((void*)&a))[*b + 1] = *value;
  ~~~~~~~~~~~~~~~~~~~~~ ^
1 error generated.
make: *** [test] Error 1

我并没有真正掌握实现这一目标的指针,想知道是否有人可以为我指明正确的方向.

I don't really have a super solid grasp of the pointers to accomplish this and wondering if one could point me in the right direction.

推荐答案

当你尝试引用一个:&a 时,你必须强制转换 void **而不是 void * 因为 a 首先是一个指针.

When you try to reference to a: &a, you have to cast void ** instead of void * because a is a pointer at first.

所以,它会起作用(我不确定这是你想要的):

So, it will work (i'm not sure it's thing you want):

 (((void**)&a))[*b + 1] = value;

这篇关于如何在C中没有结构的情况下嵌套双指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆