hello, I am trying to write this code to solve the josephus problem.
All I am getting is Segmentation Fault(coredump)? i am assuming its something to do with me using calloc but i cant tell what i've done wrong? any suggestions? thanks!
/*program to give solution of josephus problem using linear linked list*/
#include <stdio.h>
#include <stdlib.h>
struct player{
int pnumb;
struct player *next;
}player;
int main(void)
{
struct player *firstplayer, *current_player, *victim; /*define pointers*/
int k, n; /*define constants */
int i, j; /*iterative counters*/
/*input n and k from user*/
printf("enter number of people in circle: ");
scanf("%d",&n);
printf("enter k: ");
scanf("%d",&k);
/*set head of circle(first player)*/
firstplayer = current_player = (struct player*)calloc(1, sizeof(struct player));
if(!firstplayer){
printf("failed to allocate memory(1)...exiting.n");
exit(1);
}
/*create circle*/
for(i=0; i<(n-2); i++){
current_player=current_player->next=(struct player *)calloc(1, (sizeof(struct player)));
if(!current_player){
printf("failed to allocate memory(2)...exiting.n");
exit(2);
}
}
current_player->next = firstplayer; /*link tail to head of circle*/
while((sizeof(struct player)) > 1){
for (j=0; j<k;j++){ /*count k-1 places around circle*/
current_player = current_player->next;
}
current_player = current_player->next = victim; /*victim is kth player*/
while(current_player == victim){ /*eject victim by going to next player*/
printf("victim is in position %d", victim->pnumb);
free(victim);
current_player = current_player->next;
}
}
printf("last player is in position %d", current_player->pnumb);
free(firstplayer);
return 0;
}