I think that in the loop within the function create
for(i=1;i<n;i++)
you mean
last = last->next;
instead of
last=first;
Pay attention to that it is a bad idea to declare the pointer to the head node as global and when functions depend on global variables.
Also the user can pass to the function the number of elements of an array equal to 0. Also allocation of memory can fail.
I would declare the function the following way
size_t create( struct node **head, const int a[], size_t n )
{
// if the list is not empty free its nodes
while ( *head != NULL )
{
struct node *current = *head;
*head = ( *head )->next;
free( current );
}
size_t i = 0;
for ( ; i < n && ( *head = malloc( sizeof( struct node ) ) ) != NULL; i++ )
{
( *head )->data = a[i];
( *head )->next = NULL;
head = &( *head )->next;
}
return i;
}
And call the function like
size_t n = create( &first, a, sizeof( a ) / sizeof( *a ) );
In this case the function returns the number of created nodes in the list.
Here is a demonstrative program.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
size_t create( struct node **head, const int a[], size_t n )
{
// if the list is not empty free its nodes
while ( *head != NULL )
{
struct node *current = *head;
*head = ( *head )->next;
free( current );
}
size_t i = 0;
for ( ; i < n && ( *head = malloc( sizeof( struct node ) ) ) != NULL; i++ )
{
( *head )->data = a[i];
( *head )->next = NULL;
head = &( *head )->next;
}
return i;
}
void output( const struct node *head )
{
for ( ; head != NULL; head = head->next )
{
printf( "%d -> ", head->data );
}
puts( "null" );
}
int main(void)
{
struct node *head = NULL;
int a[] = { 1, 2, 3, 4 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t n = create( &head, a, N );
printf( "There are %zu nodes in the list\n", n );
printf( "They are " );
output( head );
return 0;
}
Its output is
There are 4 nodes in the list
They are 1 -> 2 -> 3 -> 4 -> null