gpt4 book ai didi

c - 段错误(核心转储)问题,堆栈

转载 作者:行者123 更新时间:2023-11-30 19:56:37 25 4
gpt4 key购买 nike

我不知道我哪里出了问题,任何帮助都会有所帮助。我正在尝试用 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;
}

最佳答案

您不能使用 strcat(rankTemp,suitTemp); 因为 rankTemp 指向字符串文字,通过这样做,您将修改非法内存指令的字符串文字,并且操作系统可以检测到对有效内存的无效访问,然后操作系统发送 SIGSEGV 导致 core dump。

关于c - 段错误(核心转储)问题,堆栈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22015162/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com