C -- Trouble with initializing dynamic list - c

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;
}
}
}

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, &current_d, &head_p, &current_p);

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.

Related

Program crashes when using free() on an array of structure that was created by calloc

I have this function which is using calloc to create an array of structure proposition. Whenever I try to free the resulting array from another fuction, it crashes.
proposition* get_matching_propositions(char *pcde, proposition *propositions, int *match_count)
{
proposition *matches;
int count = get_count_from_stream(ptf_proposition, sizeof(proposition)),
cptr_match = 0;
for (int i = 0; i < count; i++)
{
if (strcmp(propositions[i].cde, pcde) == NULL)
{
cptr_match++;
}
}
matches = (proposition*) calloc (cptr_match, sizeof(propositions));
assert(matches != NULL);
cptr_match = 0;
for (int i = 0; i < count; i++)
{
if (strcmp(propositions[i].cde, pcde) == NULL)
{
matches[cptr_match] = propositions[i];
cptr_match++;
}
}
*match_count = cptr_match;
return matches;
}
Inside some other function I have:
proposition *matches =
get_matching_propositions(current_question.cde, propositions, &match_count);
free(matches);
Then the program crashes with this message :
Process returned -1073740940 (0xC0000374) execution time : 1.370 s.

how to see if there are 1 or 2 poker pairs in a hand in C

I am trying to develop a C program that checks if there are 1 or 2 pairs in a 5 card poker hand.
I am using a 5x3 array where every line is a card (the 3rd column being for the \0 character). Every time I execute the code it always shows the "two pairs" print.
I want to make sure that each letter (i, j, a, b) representing each line is different. Any help?
P.S.: This is for a university/college project, I have only started programming a few months ago from absolute scratch, so any detailed explanations on my mistakes would be very much appreciated :)
#include <stdio.h>
#include <stdlib.h>
char (cards[5][3])=
{
"5S", "6D", "4H", "KD", "5C"
};
int main ()
{
pair (cards[5][3]);
return 0;
}
void pair (char (arg[n][0]))
{
int i,j,a,b;
if (i!=j!=a!=b)
{
if ((arg[i][0]==arg[a][0])&&(arg[b][0]!=arg[j][0]))
{
printf("2 -> pair");
}
if ((arg[i][0]==arg[a][0])&&(arg[b][0]==arg[j][0]));
{
printf("3 -> two pairs");
}
if ((arg[i][0]!=arg[a][0])&&(arg[b][0]!=arg[j][0]))
{
printf("there is no pair");
}
}
else
{
printf("there is no pair");
}
}
The posted code has several issues, both logical and syntactical, some have been pointed out in the comments.
Just to pick one, consider this line
if ((arg[i][0]==arg[a][0])&&(arg[b][0]==arg[j][0]));
{
// This body will never be executed ^
}
I'd suggest to restart from scratch and to proceed in small steps. See, for instance, the following minimal implementation
// Include all the needed header files, not the unneeded ones.
#include <stdio.h>
// Declare the functions prototype before their use, they will be defined after.
int count_pairs(int n, char const cards[][3]);
// Always specify the inner size, ^ when passing a multidimensional array
void show_score(int n_pairs);
int have_the_same_value(char const *a, char const *b);
int main (void)
{
char hand[5][3] = {
// ^^^^^^ You could omit the 5, here
"5S", "6D", "4H", "KD", "5C"
};
int n_pairs = count_pairs(5, hand);
// Always pass the size ^ if there isn't a sentinel value in the array
show_score(n_pairs);
return 0;
}
// This is a simple O(n^2) algorithm. Surely not the best, but it's
// a testable starting point.
int count_pairs(int n, char const cards[][3])
{
// Always initialize the variables.
int count = 0;
// Pick every card...
for (int i = 0; i < n; ++i)
{
// Compare (only once) with all the remaining others.
for (int j = i + 1; j < n; ++j)
{ // ^^^^^
if ( have_the_same_value(cards[i], cards[j]) ) {
++count;
}
}
}
return count;
}
int have_the_same_value(char const *a, char const *b)
{
return a[0] == b[0];
}
// Interpret the result of count_pairs outputting the score
void show_score(int n_pairs)
{
switch (n_pairs)
{
case 1:
printf("one pair.\n");
break;
case 2:
printf("two pairs.\n");
break;
case 3:
printf("three of a kind.\n");
break;
case 4:
printf("full house.\n");
break;
case 6:
printf("four of a kind.\n");
break;
default:
printf("no pairs.\n");
}
}
Note that my count_pairs function counts every possible pair, so if you pass three cards of the same kind, it will return 3 (given AC, AS, AD, all the possible pairs are AC AS, AC AD, AS AD).
How to correctly calculate all the poker ranks is left to the reader.
Major improvements can be made to the pair function to make it slimmer. However, this answers your questions and solves several corner cases:
#include <stdio.h>
#include <stdlib.h>
void pairCheck(char hand[][2])
{
int pairCount = 0;
int tmpCount = 0;
char tmpCard = '0';
char foundPairs[2] = {0};
// Check Hand One
for(int i =0; i < 5; i++)
{
tmpCard = hand[i][0];
for(int j = 0; j < 5; j++)
{
if(tmpCard == hand[j][0] && i != j)
{
tmpCount++;
}
if(tmpCount == 1 && (tmpCard != foundPairs[0] && tmpCard != foundPairs[1]))
{
foundPairs[pairCount] = tmpCard;
pairCount++;
}
tmpCount = 0;
}
}
printf("Pair Count Hand One: %i\r\n",pairCount);
//Reset Variables
foundPairs[0] = 0;
foundPairs[1] = 0;
tmpCard = '0';
pairCount = 0;
// Check Hand One
for(int i =0; i < 5; i++)
{
tmpCard = hand[i][1];
for(int j = 0; j < 5; j++)
{
if(tmpCard == hand[j][1] && i != j)
{
tmpCount++;
}
if(tmpCount == 1 && (tmpCard != foundPairs[0] && tmpCard != foundPairs[1]))
{
foundPairs[pairCount] = tmpCard;
pairCount++;
}
tmpCount = 0;
}
}
printf("Pair Count Hand Two: %i",pairCount);
}
int main ()
{
char cards[5][2] = { {'5','H'},{'6','D'},{'4','H'},{'K','D'},{'5','C'}};
pairCheck(cards);
return 0;
}
This function will treat three, four, or five of a kind as a single pair. If you want a different behavior the change should be easy.

C: Where should I free my pointers?

I'm a student and I'm trying to complete a task in C right now.
I've written an algorithm, which works fine so far. It gets a file to detect if the included logical expression is satisfiable (SAT-Solver). The problem is, that I get a Segementation Fault after a while, when I'm trying to use it with bigger files (about 60MB). I think it is, because I use malloc a couple times, but I don't free that memory yet, because I don't know where to put the free() expresseions.
There's one method, which calls itself twice everytime. The code looks like this:
int DPLL (int *pointer, int variablen, int anzahlklauseln)
{
int newliteral;
int neueklauseln;
int *neuphi;
int *neuphi2;
int *unitclauses;
int *pureliterals;
int offsetzaehler;
int rek1, rek2;
klauseln = anzahlklauseln;
unitclauses = (int *) malloc(klauseln * sizeof(int));
pureliterals = (int *) malloc(variablen * sizeof(int));
if (isEmpty())
{
return 1;
}
if (ContainsEmptyClause(pointer, variablen))
{
return 0;
}
unitClauses(pointer, variablen, unitclauses);
if (unsatisfiable)
{
unsatisfiable = 0;
return 0;
}
int iunitclauses = 0;
while (unitclauses[iunitclauses] != 0)
{
unitPropagate(pointer, variablen, unitclauses[iunitclauses++]);
}
if (quicksati(pointer, variablen))
{
return 1;
}
pureLiterals(pointer, variablen, pureliterals);
int ipureliterals = 0;
while (pureliterals[ipureliterals] != 0)
{
pureLiteralAssign(pointer, variablen, pureliterals[ipureliterals++]);
}
if (quicksati(pointer, variablen))
{
return 1;
}
newliteral = chooseliteral(pointer, variablen);
neuphi = (int*) malloc(variablen * (klauseln + 1) * sizeof(int));
neuphi2 = (int*) malloc(variablen * (klauseln + 1) * sizeof(int));
int *hilfspointer = pointer;
offsetzaehler = 0;
for (int i = 0; i < (klauseln +1); ++i)
{
for (int j = 0; j < variablen; ++j)
{
if (i == klauseln)
{
neuphi[offsetzaehler] = 0;
neuphi2[offsetzaehler] = 0;
}
else
{
neuphi[offsetzaehler] = *hilfspointer;
neuphi2[offsetzaehler++] = *hilfspointer++;
}
}
}
neueklauseln = klauseln + 1;
addClause(neuphi, variablen, newliteral);
addClause(neuphi2, variablen, (-newliteral));
if (DPLL(neuphi, variablen, neueklauseln))
{
return 1;
}
else
{
return DPLL(neuphi2, variablen, neueklauseln);
}
}
Now I thought I should edit the last lines like this:
rek1 = DPLL(neuphi, variablen, neueklauseln);
rek2 = DPLL(neuphi2, variablen, neueklauseln);
free(neuphi);
free(neuphi2);
free(unitclauses);
free(pureliterals);
return rek1 || rek2;
But then I'll get segmentation fault errors for files, which worked before.
Then I tried it like this:
if (DPLL(neuphi, variablen, neueklauseln))
{
return 1;
}
else
{
free(neuphi);
free(unitclauses);
free(pureliterals);
rek1 = DPLL(neuphi2, variablen, neueklauseln);
free(neuphi2);
return rek1;
}
But then I'd get even more Segmentation Faults.
So any C experts here, who'd like to help me? Thanks alot! :)
Your recursion doesn't have an exit condition, so the program will encounter segmentation fault when it hits stack overflow or when your malloc call returns null pointer as consequence of running out of heap memory, whatever happens first.

Initializing Strings in an Array of Sturts within a Struct

I have a struct gradebook with(among other things) an array of student structs that has two string fields
#define MAX_NAME_LEN 50
#define MAX_EMAIL_LEN 80
#define MAX_NUMBER_OF_STUDENTS 200
#define MAX_NUMBER_OF_ASSIGNMENTS 100
typedef struct students {
char *name;
char *email;
} Students;
typedef struct gradebook {
int number_of_students;
Students students[MAX_NUMBER_OF_STUDENTS];
int number_of_assignments;
char assignments[MAX_NUMBER_OF_ASSIGNMENTS][(MAX_NAME_LEN + 1)];
int scores[MAX_NUMBER_OF_STUDENTS][MAX_NUMBER_OF_ASSIGNMENTS];
} Gradebook;
I have an initialization function
int init_gradebook(Gradebook *book) {
int row, col, ndx, count;
book->number_of_students = 0;
count += book->number_of_students;
for(ndx = 0; ndx < MAX_NUMBER_OF_STUDENTS; ndx++) {
book->students[ndx].name = 0;
book->students[ndx].email = 0;
}
book->number_of_assignments = 0;
count += book->number_of_assignments;
for(row = 0; row < MAX_NUMBER_OF_ASSIGNMENTS; row++) {
for(col = 0; col < (MAX_NAME_LEN + 1); col++) {
book->assignments[row][col] = 0;
count += book->assignments[row][col];
}
}
for(row = 0; row < MAX_NUMBER_OF_STUDENTS; row++) {
for(col = 0; col < MAX_NUMBER_OF_ASSIGNMENTS; col++) {
book->scores[row][col] = 0;
count += book->scores[row][col];
}
}
if (count == 0) {
return 1;
} else {
return 0;
}
}
and I need to then insert, into those two string fields, the passed in strings, with my add_student function.
int add_student(Gradebook *book, char *nom, char *mail) {
int ndx, count;
if (book->number_of_students == 0) {
book->students[(book->number_of_students)].name = malloc(sizeof(51));
book->students[(book->number_of_students)].email = malloc(sizeof(81));
strcpy(book->students[(book->number_of_students)].name, nom);
strcpy(book->students[(book->number_of_students)].email, mail);
book->number_of_students++;
} else {
for (ndx = 0; ndx < book->number_of_students; ndx++) {
book->students[(book->number_of_students)].name = malloc(sizeof(51));
book->students[(book->number_of_students)].email = malloc(sizeof(81));
strcpy(book->students[(book->number_of_students)].name, nom);
strcpy(book->students[(book->number_of_students)].email, mail);
book->number_of_students++;
}
}
return 1;
}
My code compiles, but when I run it with the main function, I get a seg fault. The add_student function is what I am ultimately trying to do (copy the given string into book->student[ndx].name) If you need to see the main file or the gradebook.h file, let me know.
Edit: Thanks to all of you, this issue has been solved. The main problem, as abginfo pointed out, was my If Else + the For loop inside of it. But now I have other problems further along in my program. Haha, Thank You.
From what portion of your code I can see, I'm going to make the assumption that the init_gradebook function takes a non allocated reference to gradebook and attempts to initialize it.
In this case the gradebook reference you have has no memory allocated to it just yet. Try using the malloc() function to assign the required memory to your gradebook reference before attempting to initialize the rest of its variables.
gb = (Gradebook*)malloc(sizeof(*Gradebook));
I've changed the variable name to avoid any confusion.
To supplement varevarao's answer, you should allocate everything explicitly as a matter of habit instead of relying on segfaults to tell you something's not allocated. (Not that you necessarily do!) Messing with unallocated memory is undefined behavior, so in some cases this code does not trigger an error -
int main (void) {
Gradebook mybook;
init_gradebook(&mybook);
printf("there are %i students\n", mybook.number_of_students);
add_student(&mybook, "blerf", "blerf#gmail.com");
printf("now there are %i students\n", mybook.number_of_students);
printf("%s has an email address of %s\n", mybook.students[0].name, mybook.students[0].email);
return 0;
}
returned (on my machine)
there are 0 students
now there are 1 students
blerf has an email address of blerf#gmail.com

C, card game WAR

I am trying to create a War card game using C. Instead of making 2 decks for the "discarded" cards to be added to a players hand at a later time, I am instead just trying to add the dealers card[i] - which was previously compared with players card[i] to ensure that the player won the hand - to the players hand directly. index is used to make sure there are no empty elements playerhand ever points to by appending another card on to the end of the “hand,” which initially has 26 cards (half the deck). the deck is initially split in 2, the first 26 cards deck[0-25] going to the player's hand, and the last 26 deck[26-51] going to the dealers hand.
here is my code in question:
//adds new card to deck at given index
void addToPlayerHand(int i) {
int index=0;
playerHand[index+26] = deck[i+26];
index++;
}
here is my full game code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
//Type Stucture for Card
typedef struct cards {
char suit;
int face;
struct cards *listp; // didn't use in this program
} card;
//Functions
//
int welcome();
//int checkWinWar();
int playGame();
int getComparison(card *firstCard,card *secndCard,int index);
void printingGame(int a,int b, int i);
void addToPlayerHand(int i);
void addToDealerHand(int i);
int addToDeck(card myCards, int index);
void hitPlayer(card theCard);
void hitDealer(card theCard);
void initilizeDeck();
int shuffleDeck();
int printFun(); // not used for game play
void freePlayers();
//Card Dynamics
//
card *playerHand; // contains contents of players cards
card *dealerHand; // contains contents of dealers cards
//Deck of 52 Cards with discard decks
card deck[52];
card playerDeck[52];
card dealerDeck[52];
int numPlayer = 0;
int numAllPlayer = 0;
int numDealer = 0; // needed for temp
int numAllDealer = 0;
//Main
int main(void) {
printf("Hello..Welcome to WAR\n");
//Game loop
while (welcome() == 1) { // welcome returns whether the player wants to play (1) or not (0)
// put first card face up
// display how many cards
// indicate (if/if no) war has occurred
// complete the war
// add cards to player discard pile
// check player for card count
// if end game conition met, end hame
if(playGame() == 1) { // playGame returns 1 if the function went through correctly
if(checkWinWar()==1){
}
else{
}
} else {
printf("Bust! Try Again\n\n");
freePlayers(); // refreshes the dynamics of the hands
}
}
//initilizeDeck();
//shuffleDeck();
//printFun();
return 0;
}
//To allow the player to begin the game; 1 = True 0 = False
int welcome() {
printf("Play a new round of WAR? (enter/return for yes):\t");
if(getchar()=='\n'){
return 1;
}
else
return 0;
}
// refreshes the game and players
void freePlayers () {
numDealer = 0;
numPlayer = 0;
numAllPlayer = 0;
numAllDealer = 0;
free(playerHand);
free(dealerHand);
playerHand = NULL; // needed so playerHand doesn't point to anything
dealerHand = NULL;
return;
}
// Playing of the game
int playGame() {
initilizeDeck(); // initialize Deck returns the new deck of cards
shuffleDeck(); // shuffleDeck returns the shuffled deck of cards
int gameTrue = 1; // gameTrue checks the state of the game
int war = 0;
int PlayerCardsRemaining=0;
int DealerCardsRemaining=0;
int temp,i,j=0;
while (gameTrue == 1) {
// splitting the deck
for (j=0;j<26;j++){
hitPlayer(deck[j]); // adding cards to playerHand
PlayerCardsRemaining+=1; //adding to player deck count.
}
for (j=26;j<52;j++){
hitDealer(deck[j]);
DealerCardsRemaining+=1;} // adding to dealer deck count.
i=0;
while(PlayerCardsRemaining>0 && DealerCardsRemaining>0 && i<26) {
printingGame(DealerCardsRemaining,PlayerCardsRemaining, i);
if (getComparison(playerHand, dealerHand, i)==0){
addToDealerHand(i);
DealerCardsRemaining++;
return 1;
}
else if(getComparison(playerHand,dealerHand,i)==1){
addToPlayerHand(i);
PlayerCardsRemaining++;
return 1;
}
else if(getComparison(playerHand, dealerHand, i)==2){
printf("There is an impending WAR\n");
printf("press enter to engage in the WAR");
war=1;
if(war==1 && DealerCardsRemaining>=4 && PlayerCardsRemaining>=4){
temp=getComparison(playerHand, dealerHand, i+4);
while(war==1){
if(temp==0){
for(i=i;i<i+4;i++){
addToDealerHand(i);
}
war=0;
PlayerCardsRemaining-=4;
DealerCardsRemaining+=4;
}
else if(temp==1){
for(i=i;i<i+4;i++){
addToPlayerHand(i);
}
war=0;
DealerCardsRemaining-=4;
PlayerCardsRemaining+=4;
}
else
war=1;
}
return 1;
}
if (DealerCardsRemaining<<4){
for(i=i;i<i+4;i++){
addToPlayerHand(i);
}
}
else if (PlayerCardsRemaining<<4){
for(i=i;i<i+4;i++){
addToDealerHand(i);
}
}
}
i++; // increment i
}
}
return 0;
}
void printingGame(int DealerCardsRemaining, int PlayerCardsRemaining, int i)
{
// Gameplay Prompts
//Prints interface that comes up after player(s) choose to play
printf("*********\t\t*********\n");
printf("*\t \t*\t\t*\t \t*\n");
// Cases for cards that are face cards
if(dealerHand[i].face==11){ // if dealer card is a jack
printf("*\tJ\t*\t\t");
if (playerHand[i].face<11){ // if player card isnt a face card
printf("*\t%d\t*\n",playerHand[i].face);
}
else if(playerHand[i].face==11){ // if player card is a face card
printf("*\tJ\t*\n");
}
else if(playerHand[i].face==12){
printf("*\tQ\t*\n");
}
else if(playerHand[i].face==13){
printf("*\tK\t*\n");
}
else if(playerHand[i].face==14){
printf("*\tA\t*\n");
}
}
else if(dealerHand[i].face==12){ // if dealer card is a queen
printf("*\tQ\t*\t\t");
if (playerHand[i].face<11){ // if player card isnt a face card
printf("*\t%d\t*\n",playerHand[0].face);
}
else if(playerHand[i].face==11){ // if player card is a face card
printf("*\tJ\t*\n");
}
else if(playerHand[i].face==12){
printf("*\tQ\t*\n");
}
else if(playerHand[i].face==13){
printf("*\tK\t*\n");
}
else if(playerHand[i].face==14){
printf("*\tA\t*\n");
}
}
else if(dealerHand[i].face==13){ // if dealer card is a king
printf("*\tK\t*\t\t");
if (playerHand[i].face<11){ // if player card isnt a face card
printf("*\t%d\t*\n",playerHand[i].face);
}
else if(playerHand[i].face==11){ // if player card is a face card
printf("*\tJ\t*\n");
}
else if(playerHand[i].face==12){
printf("*\tQ\t*\n");
}
else if(playerHand[i].face==13){
printf("*\tK\t*\n");
}
else if(playerHand[i].face==14){
printf("*\tA\t*\n");
}
}
else if(dealerHand[i].face==14){ // if dealer card is an ace
printf("*\tA\t*\t\t");
if (playerHand[i].face<11){ // if player card isnt a face card
printf("*\t%d\t*\n",playerHand[i].face);
}
else if(playerHand[i].face==11){ // if player card is a face card
printf("*\tJ\t*\n");
}
else if(playerHand[i].face==12){
printf("*\tQ\t*\n");
}
else if(playerHand[i].face==13){
printf("*\tK\t*\n");
}
else if(playerHand[i].face==14){
printf("*\tA\t*\n");
}
}
if (dealerHand[i].face<11 && playerHand[i].face<11){ // if both cards arent face cards
printf("*\t%d\t*\t\t*\t%d\t*\n",dealerHand[i].face,playerHand[i].face);
}
printf("*\t \t*\t\t*\t \t*\n");
printf("*********\t\t*********\n");
printf("Dealer: %d cards. ",DealerCardsRemaining); // print how many cards the 'dealer' has
printf("Player: %d cards. ",PlayerCardsRemaining); // print how many cards the player has
}
int getComparison (card *firstCard, card *secndCard, int i)
{
int a,b;
a=firstCard[i].face;
b=secndCard[i].face;
if (b>a)
return 0;
else if (a>b)
return 1;
else
return 2;
}
// gives player another card
void hitPlayer (card theCard) {
if(numPlayer == 0) { // if hitPlayer is giving playerHand its first card (for new deck or initial deck)
if (numAllPlayer == 0) // if its the first hand
numAllPlayer = 1; // there is only one card in need of space
else // if its not the first hand
numAllPlayer++; // you need space for all existing cards plus the one just added
void *_tmp = realloc(playerHand, (numAllPlayer * sizeof(card))); // realloc is used since playerHand never has a constant size
if (!_tmp)
{
fprintf(stderr, "ERROR: Couldn't realloc memory!\n"); // stderr prints
}
playerHand = (card*)_tmp; // playerHand is card type pointer which points to void pointer tmp which is reallocating memory
}
playerHand[numPlayer] = theCard;
numPlayer++;
}
// gives dealer another card
void hitDealer (card theCard) {
if(numDealer == 0) {
if (numAllDealer == 0)
numAllDealer = 1;
else
numAllDealer++;
void *_tmp = realloc(dealerHand, (numAllDealer * sizeof(card)));
if (!_tmp)
{
fprintf(stderr, "ERROR: Couldn't realloc memory!\n");
}
dealerHand = (card*)_tmp;
}
dealerHand[numDealer] = theCard;
numDealer++;
}
// creates a new deck of cards
void initilizeDeck() {
//Loop Indexes like: count, i.... etc
int i, p;
int count = 0;
card temp;
for (i = 1; i < 5; i++) {
for (p = 2; p <= 14; p++) {
//Clubs
if (i == 1) {
temp.suit = 'C';
temp.face = p;
}
//Diamonds
if (i == 2) {
temp.suit = 'D';
temp.face = p;
}
//Hearts
if (i == 3) {
temp.suit = 'H';
temp.face = p;
}
//Spades
if (i == 4) {
temp.suit = 'S';
temp.face = p;
}
addToDeck(temp, count);
count++;
}
}
}
//adds new card to deck at given index
int addToDeck(card myCards, int index) {
deck[index] = myCards;
return 1;
}
//adds new card to deck at given index
void addToPlayerHand(int i) {
int index=0;
playerHand[index+26] = deck[i+26];
index++;
}
//adds new card to deck at given index
void addToDealerHand(int i) {
int index=0;
dealerHand[index+26] = deck[i];
index++;
}
//finds deck and shuffles cards 100 times from swaping a random value from 1-52
int shuffleDeck() {
card temp; // for an individual card
int i,p;
srand(time(NULL));
for (i = 0; i < 100; i++) {
for (p = 0; p < 52; p++) {
int r = rand()%52;
temp = deck[p]; // swaps to randomly pick another card
deck[p] = deck[r];
deck[r] = temp;
}
}
return 0;
}
it keeps telling me i have a bad access code, code=2.
any help would be awesome.
I'll dispense with the "I'd never code this that way" dialogue long enough to suggest that this loop ideology:
for(i=i;i<i+4;i++)
will look well past the limits of your card arrays and into the land of undefined behavior. Think about it a minute. Then ask yourself this question: At what point will i no longer be less than i+4 ? Answer: when you reach the point when i+4 overflows to become negative (assuming the optimizer doesn't throw out the condition entirely and just assume it is always true; thanks Jeremy).
I.e. INT_MAX-3. On a 32-bit system that is only about 2147483562 slots past the end of your array.
This error is repeated 3 more times in the playGame() function.

Resources