E.U. said:
Hello,
I wanted to know what does the following code lines mean?
**p=&(list->m_head);
p=&((*p)->m_next);
What does the second line mean? I thought I should write
*p=&((*p)->m_next); with a star at the beginning of the line. Since
this is a pointer to pointer and what I want that the last pointer
points to the next node. But I understood that I should remove the
star if I want that and I don't understand why. As I see it without
the star I am having the first pointer point to the next node (and
that impossible since its a pointer to pointer and the first pointer
should point to an address.)
Where am I wrong?
This code might to be part of an algorithm that traverses a
linked list for the purpose of adding to the tail of the list.
If this assumption is correct then you will have a struct object
that has as a member 'next' which will point to the next struct
object in the list. The code you are describing is frequently used
to traverse to the tailend of the list for the purpose of adding
another object to the end of the list.
You will have a struct definition, for example, lets call it
struct employee
The you have the declarations:
struct employee *head = NULL;
struct employee **p;
Type p is a pointer to a pointer to the struct object.
Type *p is a pointer to the struct object.
Type **p is the struct object.
The algorithm can be in the form of a for loop.
for(p = &head; *p != NULL; p = &((*p)->next)) ;
The for loop will traverse to the end of the list and
p will be the address of the stuct pointer where a pointer
to a new struct object will be added. It is done in the form
*p = pointer_to_new_object;
Here is a working example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct EMPLOYEES
{
char name[60];
unsigned age;
struct EMPLOYEES *next;
};
int AddEMPLOYEE(struct EMPLOYEES **p, const char *name, unsigned age)
{
struct EMPLOYEES *new, **tmp;
if((new = malloc(sizeof *new)) == NULL) return 0;
strncpy(new->name,name,60);
new->name[59] = '\0';
new->age = age;
new->next = NULL;
for(tmp = p ; *tmp; tmp = &((*tmp)->next)) ;
*tmp = new;
return 1;
}
void FreeEMPLOYEES(struct EMPLOYEES **p)
{
struct EMPLOYEES *tmp;
for( ; *p; *p = tmp)
{
tmp = (*p)->next;
free(*p);
}
}
int main(void)
{
struct EMPLOYEES *Sears = NULL, *tmp;
size_t i = 1;
AddEMPLOYEE(&Sears, "John Doe",32);
AddEMPLOYEE(&Sears, "Jane Smith",29);
/* Print the list */
for(tmp = Sears ; tmp; tmp = tmp->next)
printf("Employee %u.\n\tname: %s\n\tage: %u\n\n",
i++,tmp->name,tmp->age);
/* Free the list */
FreeEMPLOYEES(&Sears);
if(!Sears) puts("List Freed and Sears = NULL");
return 0;
}