我已经编写了一个 C 代码来使用交换逻辑洗牌一副 52 张牌。该代码生成一个介于 0 到 53 之间的随机数(52 和 53 被省略),然后将其与数组中的第 i 个索引交换。代码如下。
我的问题: 当我在调用 swap() 函数之前注释掉 display() 函数调用时,程序会抛出一个段错误。但是当我取消注释并在调用 swap() 函数之前调用显示函数时,程序工作正常并且我得到了所需的输出。我不知道为什么会这样。
主要功能:
int main()
{
char deck[] = {'2','3','4','5','6','7','8','9','0','A','J','K','Q'};
char suit[] = {'D','H','S','C'};
char **array,**array1;
array = malloc(sizeof(char *)*52);
array1= array;
srand(time(NULL));
for(int i=0;i<=12;i++)
{
for(int j=0;j<=3;j++)
{
if((*array = malloc(sizeof(char)*2))!=NULL)
{
sprintf(*array,"%c%c",deck[i],suit[j]);
*array++;
}
}
}
//display(array1); // when i comment this line, the program throws segfault. when i uncomment it the program runs fine.
swap(array1);
display(array1);
free_array(array1);
return 0;
}
这是交换和显示的其他功能。
void display(char **array)
{
char **temp;
temp = array;
for(int i=0;i<=51;i++)
{
printf("temp [%s]\n",*temp);
*temp++;
}
return;
}
void swap(char **array)
{
char **temp;
int x;
temp = array;
char *temp1;
for(int i=0;i<=51;i++)
{
x = rand()%53;
if(x == 53 || x == 52)
continue;
memcpy(temp1,temp[i],2); // program segfaults here.
memcpy(temp[i],temp[x],2);
memcpy(temp[x],temp1,2);
}
return;
}
最佳答案
在交换函数中 -
您正在使用 temp1 而未对其进行初始化。
void swap(char **array)
{
char **temp;
int x;
temp = array;
char temp1[ 2 ];
for(int i=0;i<=51;i++)
{
x = rand()%53;
if(x == 53 || x == 52)
continue;
// need to multiply the indexes by 2
// allowing for the suit and deck
memcpy(temp1,temp[ i ],2); // program segfaults here.
memcpy(temp[ i ],temp[ x ],2);
memcpy(temp[ x ],temp1,2);
}
}
上面显示 temp1 正确初始化。
我还没有检查你的函数的其余部分,但这将停止段错误。
关于c - 段错误 SEGV_ACCERR - 对象的无效权限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46053747/