You don't use pointer arithmetic in linked list implementations, at least not trivial ones. And you're populating your list incorrectly. You need to retain the head pointer. This is one such way to do it:
// Note: do NOT invoke on a non-empty pNode list
void CreateLinkedList()
{
node **pp = &pNode;
int i;
for (i=0;i<10;++i)
{
*pp = malloc(sizeof(**pp));
(*pp)->element = i;
pp = &(*pp)->nextPtr;
}
*pp = NULL;
}
How It Works
Just like pNode
is a pointer to a node
, pp
is a pointer to a node *
. During the lifetime of the loop pp
always holds the address of the next pointer about to be filled with a new node allocation. After the allocation and node setup, pp
is filled with the address of the nextPtr
pointer of the node just-created. This continues until the end of the fill. At that point the pointer addressed by pp
is the tail nextPtr
and should be null-terminated (which is what *pp = NULL
does). Step through this code in a debugger to see better how it works.
Personally I would pass the address of the head pointer as a parameter, but this is one immediate way to get your code running.