I'm still slowly trying to understand pointers, and am confused as to why the correct 'head' parameter is not being passed to length() in the following code for an attempted 'linked list'. Hope someone can explain where I'm erring.
Code:
#include <stdio.h>
#include <stdlib.h>
#define MAX 3
struct node
{
int data;
struct node* next;
};
struct node* head;
//prototypes
int length(struct node*);
struct node* push(struct node*, int);
int main(void)
{
struct node* head = NULL;
for(int i=1;i<=MAX;i++)
{
push(head, i);
}
//int len = length(head);
}
struct node* push(struct node* head, int a)
{
struct node* newNode;
newNode = malloc(sizeof(struct node));
head = newNode;
newNode->data = a;
newNode->next = NULL;
//function call
int len = length(head);
printf("count is %d\n",len);
return head;
}
int length(struct node* current)
{
int count = 0;
current= head;
while(current!= NULL)
{
count++;
current = current->next;
}
return count;
}
If struct node* head is global, shouldn't it be passed properly to length() in my code?