繁体   English   中英

如何正确传递空指针?

[英]How to pass void pointer around correctly?

我想将我的结构指针作为空指针返回。 在这个函数中,当我打印 noOfTuples 时,我正确地得到了零。

typedef void* HashjoinDatabase;
HashjoinDatabase HashjoinAllocateDatabase(unsigned long totalNumberOfEdgesInTheEnd) {
  HashjoinDatabase db;
  
  struct database* d = malloc(sizeof(struct database));
  if(d == NULL) {
    puts("Some kind of malloc() error");
  }

  d->tuples = malloc(totalNumberOfEdgesInTheEnd * sizeof(struct tuple));
  if(d->tuples == NULL) {
    puts("Some kind of malloc() error");
  }

  d->noOfTuples = 0;
  db = &d;
  printf("Hello %i\n", d->noOfTuples);
  return db;
}

但是,当在 main 中时,我将返回的 void 指针强制转换回结构体指针并尝试获得相同的 noOfTuples 并且每次运行时我都会得到很大的变化值,我怀疑这些值是地址

int main() {
  HashjoinDatabase testDB = HashjoinAllocateDatabase(10);
  int no = ((struct database*)testDB)->noOfTuples;
  printf("Hello %i", no);
  return 0;
}
struct database* d = malloc(sizeof(struct database));

d是“指向struct database指针”类型。

db = &d;
// ...
return db;

您正在分配给db ,并将地址返回到“指向struct database指针”。

int no = ((struct database*)testDB)->noOfTuples;

您解读“指针的地址struct database ”的“指针struct database ”,所以noOfTuples没有这样的事。

这就是为什么您应该传递“指向数据类型的指针”,而不是“指向void指针”(并避免强制转换)的原因,这样编译器实际上可以在类型错误时警告您。 ;-)

你让事情变得比它们更复杂。

你可能想要这个:

struct database* HashjoinAllocateDatabase(unsigned long totalNumberOfEdgesInTheEnd) {
  struct database* d = malloc(sizeof(struct database));
  if (d == NULL) {
    puts("Some kind of malloc() error");
    exit(1);
  }

  d->tuples = malloc(totalNumberOfEdgesInTheEnd * sizeof(struct tuple));
  if (d->tuples == NULL) {
    puts("Some kind of malloc() error");
    exit(1);
  }

  d->noOfTuples = 0;                    // why put this to 0 btw?
  printf("Hello %i\n", d->noOfTuples);  // shouldn't it be rather totalNumberOfEdgesInTheEnd ?
  return d;
}


int main() {
  struct database *testDB = HashjoinAllocateDatabase(10);
  int no = testDB->noOfTuples;
  printf("Hello %i", no);
  return 0;
}

这里不需要使用void* 也不需要在 typedef 后面隐藏指针类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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