Reputation: 53
I'm having trouble with the deal function in a blackjack program I am writing. Can anyone see what is going on? When I try to print in main(), I get a segmentation fault.
Cheers.
MAIN FUNCTION
int main(void)
{
int i, j, k, purse;
card deck[52];
card *head_d, *temp_d, *current_d = NULL, *last_d, *head_p, *temp_p, *current_p = NULL, *last_p;
make(deck); //CREATES THE DECK
shuffle(deck); //SHUFFLES THE DECK
deal(deck, head_d, current_d, head_p, current_p)
for(i = 0; i < DECK_SIZE; i++)
{
printf("%d: %d %c\n", i + 1, deck[i].face, deck[i].suit);
}
temp_p = head_p;
while(temp_p != NULL)
{
printf("%d %c\n", temp_p->face, temp_p->suit);
temp_p = temp_p->listp;
}
return(0);
}
FUNCTION deal()
void deal(card x[DECK_SIZE], card *head_d, card *current_d, card *head_p, card *current_p)
{
int i;
card *temp_p, *temp_d;
for(i = 0; i < 4; i++)
{
if( i % 2 == 0)
{
temp_p = (card *)malloc(sizeof(card));
temp_p->face = x[i].face;
temp_p->suit = x[i].suit;
if (current_p==NULL)
{
head_p=temp_p;
}
else
{
current_p->listp=temp_p;
}
current_p = temp_p;
temp_p->listp = NULL;
}
else
{
temp_d=(card *)malloc(sizeof(card));
temp_d->face = x[i].face;
temp_d->suit = x[i].suit;
if (current_d==NULL)
{
head_d=temp_d;
}
else
{
current_d->listp=temp_d;
}
current_d = temp_d;
temp_d->listp = NULL;
}
}
}
Upvotes: 2
Views: 99
Reputation: 409166
The problem is that the arguments to the deal
function is local, meaning when you change their value in the function, the variables used when calling the function will not be changed. You need to pass those arguments by reference:
void deal(card x[DECK_SIZE], card **head_d, card **current_d, card **head_p, card **current_p);
The do e.g.
*head_p=temp_p;
in the function to set the variables.
Call as
deal(deck, &head_d, ¤t_d, &head_p, ¤t_p);
Upvotes: 2
Reputation: 320391
You have uninitialized pointer variable head_p
in your main
function. Yet you are attempting to read data supposedly pointed by head_p
. Of course, you will get segfault.
Upvotes: 0