[英]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.