2014-02-25 42 views
-2

我不知道我在哪里出错,任何帮助都会有所帮助。我试图从2个不同的字符串阵列中制作一副牌并将其打印到控制台。它编译罚款,但是当我运行它,我得到“分割故障(核心转储)”分割错误(核心转储)问题,堆栈

/* 
* BlackJack.c 
* 
* Created on: Feb 25, 2014 
*  Author: Danny Hunn 
*  25 Feb 14 builds a deck for Black Jack 
*/ 

#include <stdio.h> 
#include <time.h> 
#include <stdlib.h> 
#include <string.h> 
#define NUM_SUITS 4 
#define DECK_SIZE 52 
#define NUM_RANKS 13 


void swap(char *first,char *second)// swapping pointers 
{ 
char temp = *first; 
*first = *second; 
*second = temp; 

} 
void shuffle(char *deck[]) 
{ 
int seed, gen, i; 
seed = (int) time(0); 
srand(seed); 

for(i =0; i < DECK_SIZE; i++) 
{ 
     gen = rand()%52; 
     swap(deck[i],deck[gen]); 

} 

} 
void printDeck(char *deck[]) 
{ 
int i; 
for(i=0;i<DECK_SIZE; i++) 
{ 
    printf("%s\n", deck[i]); 
} 
} 

int main(int argc, char *argv[]) { 
int deckIndexs = 1; 
char *suit[NUM_SUITS] = {" Spades", " Hearts", " Diamonds", " Clubs"}; 
char *rank[NUM_RANKS] = {"Ace", "Two","Three","Four","Five","Six", "Seven", "Eight",   "Nine", 
     "Ten", "Jack", "Queen", "King"}; 
char **deck = malloc(deckIndexs * (sizeof(*deck))); 
int i,j,k; 
k=0; 
for(i=0; i< NUM_SUITS; i++) 
{ 
    for(j=0; j< NUM_RANKS; j++) 
    { 
     char *suitTemp = suit[i]; 
     char *rankTemp = rank[j]; 
     strcat(rankTemp, suitTemp); 
     deck= realloc(deck, (deckIndexs +1)*sizeof(*deck));// reallocate memory for the size of the array 
     deckIndexs++; 
     deck[k] = malloc(254*sizeof(char *));// allocate memory for the new string index 
     deck[k] = rankTemp; 
      k++;// increments k for the index of the array 
    } 

} 
printDeck(deck); 
shuffle(deck); 

return 0; 
} 
+4

不理解你的代码,双'K ++'看起来很可疑。 – unwind

+2

在调试器中运行。它会在崩溃发生时停止,并让您检查函数调用堆栈以及让您走上调用堆栈。去你的代码(如果你不在那里),你可以打印变量的值。当然,你必须用调试信息('-g'标志到gcc/clang)来构建。如果没有别的,请编辑您的问题以在发生崩溃时包含函数调用堆栈。 –

+0

请格式化您的代码。 –

回答

1

我觉得你的问题是在这里

void swap(char *first,char *second)// swapping pointers 
{ 
char temp = *first; 
*first = *second; 
*second = temp; 

} 

应该

void swap(char *first,char *second)// swapping pointers 
{ 
char * temp = first; 
first = second; 
second = temp; 

} 
5

不能使用strcat(rankTemp, suitTemp);因为rankTemp指向一个字符串,这样做你会修改字符串常量,非法内存指令,并且操作系统可以检测到对有效内存的无效访问,然后操作系统发送SIGSEGV,从而导致核心dunmp。

+0

在strcat崩溃(rankTemp,suitTemp);有关如何解决的任何建议? – drhunn

+0

@drhunn是的,首先将['char * str []'改为'char str [] []'](http://stackoverflow.com/a/17661444/1673391)保持足够大的长度,以便可以将新字符串并阅读[这个答案](http://stackoverflow.com/a/16751011/1673391) –