C - Loading a structure containing a pointer to a pointer

This generates an incompatibility warning:

#include <stdlib.h> #include <stdio.h> typedef struct { int key; int data; struct htData_* next; struct htData_* prev; }htData_; typedef struct { int num_entries; struct htData_** entries; }ht_; ht_* new_ht(int num_entries); int ht_add(ht_* ht_p, int key, int data); int main() { int num_entries = 20; //crate a hash table and corresponding reference ht_* ht_p = new_ht(num_entries); //add data to the hash table int key = 1305; ht_add(ht_p,key%num_entries,20); return 0; } ht_* new_ht(int num_entries) { ht_ *ht_p; ht_ ht; ht.num_entries = num_entries; ht_p = &ht; //create an array of htData htData_ *htDataArray; htDataArray = (htData_*) malloc(num_entries * sizeof(htData_)); //point to the pointer that points to the first element in the array ht.entries = &htDataArray; // WARNING HERE!!!!!!!!!!!!!!!! return ht_p; } 

I am trying to copy **ptr into a struct containing a **ptr .

Update: My simplified code was not accurate, so I posted the actual code.

+4
source share
2 answers

The problem is that struct htData_ and htData_ are not the same thing! As for the compiler, struct htData_ does not exist - it is an incomplete type. htData_ , on the other hand, is a typedef for an anonymous structure. For a more detailed analysis, see the section Difference between struct and typedef struct in C ++ .

So, you get a warning because ht.entries declared as a type of struct htData_** , but the right side of this assignment is of type <anonymous struct>** . To fix this, you need to define struct htData_ :

 typedef struct htData_ { ... } htData_; 
+4
source

This line is incorrect:

 htData_ array[20] = htDataArray; 

You cannot assign a pointer to an array.

In the edited code, here is the problem:

 //point to the pointer that points to the first element in the array ht.entries = &htDataArray; 

Actually, this is syntactically correct, so it should not give warnings. But you are doing the wrong stuff here. If you want ht.entries point to the first element of the array, you need to declare it as

 htData_* entries; // 'struct' keyword not needed ahead of declaration 

and assign it as,

 ht.entries = &htDataArray[0]; 
+1
source

All Articles