I'm trying to make an array of nodes,and enter values from S[] array to it. But I keep getting a segmentation fault. My struct looks like this:
typedef struct Node {
int num;
struct Node *next;
}ListNode;
Initialized array of S[10] with random numbers:
printf("list is:");
for(i=0;i<10; i++)
{
RN= (random()+1);
S[i]=RN;
printf("%d ",S[i]);
}
printf("\n");
Here is how I initialized my array of nodes:
ListNode *bucket[Radix];
for(j=0; j<Radix; j++)
{
bucket[i]=(ListNode*)malloc(sizeof(ListNode));
bucket[i]->next=NULL;
}
And this is the function I use to read array numbers from S[] into the array of linked list, bucket[]:
for(y=0;y<(sizeof(S)/sizeof(int));y++) // S is size of a normal array
{
digit=bucketNumber(S[y],1);// returns the first digit values
pointer= bucket[digit];
number= S[y];
insert_tail(pointer, number);
}
my insert_tail function look like this:
ListNode *insert_tail(ListNode *tail, int data)
// insert and element at tail
{
if (tail==NULL)
{ tail=(ListNode *)malloc(sizeof(ListNode));}
else
{
while(tail->next !=NULL)
tail->next = (ListNode *)malloc(sizeof(ListNode));
tail= tail->next;
}
tail->num= data;
tail->next=NULL;
}
this is the bucketNumber function:
int bucketNumber(int num,int digit)
{
int x, y;
y= 10*digit;
x= num%y;
if(digit>=2)
{
num= num%y;
x= num/(y/10);
}
return (x);
}
I think the reason for segmentation fault is that my function is not creating the links in the array properly. I'm not sure thou, there could be something else wrong!