Reputation: 523
I'm analyzing a bit of code and can't quite seem to grasp some of the workings behind it.
struct dplist {
dplist_node_t * head;
};
struct dplist_node {
dplist_node_t * prev, * next;
element_t element;
};
dplist_t * dpl_create ()
{
dplist_t * list;
list = malloc(sizeof(struct dplist));
DPLIST_ERR_HANDLER(list==NULL,DPLIST_MEMORY_ERROR);
list->head = NULL;
return list;
}
From the header file:
typedef int element_t;
typedef struct dplist dplist_t;
typedef struct dplist_node dplist_node_t;
In the main function:
dplist_t * list = NULL;
int main(void)
{
list = dpl_create();
return 0;
}
I'm not sure how to view the dpl_create() function which is declared as a pointer a dplist struct (i think?). Why does the function need to be declared as a pointer to a struct in order to correctly execute what is written inside the function?
Upvotes: 0
Views: 247
Reputation: 122
The first element in the declaration of a function in C, before the function's name, is always the type of the variable it will return. In your case, the function is not declared as "a pointer to a struct", it just declares that it will return a pointer to a struct ("return list"). You can see another example in your code with the main function, which will return an INT ("return 0").
Upvotes: 2
Reputation: 5238
dpl_create() allocates a new dplist_t and returns it. In C you can't return objects that are dynamically allocated, you must return a reference(pointer) to them, hence
dplist_t *
Upvotes: 0