内存错误,应该是指针问题,不知哪里出错
#include "stdlib.h "
#include "time.h "
#include "stdio.h "
int a[54];
void productcard() //产生54数值赋予数组,产生牌
{srand((unsigned)time(NULL));
int i,j;
for(i=0;i <54;i++)
{a[i]=rand()%54+1;
for(j=0;j <i;j++)
{
if(a[j]==a[i])
{
--i;
break;
}
}
//continue;
}
}
void paixu() //冒泡排序,暂时用于检测产生的数值有没有重复
{
int i,j,temp;
for(i=0;i <53;i++)
{
for(j=0;j <53-i;j++)
{
if(a[j]> a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
struct card
{
int num;
int color;
struct card *next;
};
struct card *p,*head,*player1,*player2,*player3;
//struct card *p=NULL;
//struct card *head=NULL;
//struct card *player1=NULL;
//struct card *player2=NULL;
//struct card *player3=NULL;
struct card *player[3]={player1,player2,player3};
struct card * creactlist()
{
p=(struct card *)malloc(sizeof(struct card));
head=NULL;
if(head==NULL)
{
head=p;
p-> next=NULL;
}
else
{
while(head!=NULL&&head-> next!=NULL)
{
head=head-> next;
}
if(head-> next==NULL)
{
head-> next=p;
p-> next=NULL;
}
}
return head;
}
int n,i;
struct card *card_creactlist(struct card *player[],int i)
{
for(n=0;n <17;n++)
{
p-> num=a[3*n+i+1]%13;
p-> color=a[3*n+i+1]/13;
if(p-> num==1||p-> num==2)
{
p-> num+=13;
}
if(p-> color==4)
{
p-> num+=52;
}
struct card * creactlist();
}
player[i]=head;
return player[i];
}
/*
==========================
功能:直接插入排序(由小到大)
返回:指向链表表头的指针
==========================
*/
struct card *paixu_list(struct card *player[],int i)
{
struct card *frist,*t,*k,*m;
frist=player[i]-> next;
player[i]-> next=NULL;
while(frist!=NULL)
{
for(t=frist,k=player[i];((k!=NULL)&&k-> num < t-> num);m=k,k=k-> next);
frist=frist-> next;
if(k==player[i])
{
t=player[i];
}
else
{
m-> next=t;
}
t-> next=k;
}
return player[i];
}
int main()
{
productcard();
for(i=0;i <3;i++)
{
struct card *card_creactlist(struct card *player[],int i);
struct card *paixu_list(struct card *player[],int i);
//printf( "%d\t%d\n ",player[1]-> num,player[i]-> color);
for(head=player[i];head-> next!=NULL;head=head-> next)
{
printf( "%d\t%d\n ",head-> num,head-> color);
}
//printf( "%d\t%d\n ",i,a[i]);
}
return 0;
}
程序如上,请高手帮忙看下。
调试的时候内存错误,应该是指针问题,新手自学,请回复详细些。
[解决办法]
运行调试可以通过的结论???
首先,全局变量只能用常量初始化,你的那个初始化语句根本编译不过去,我暂且当它能编译过去吧,
然后,从main函数开始执行,productcard应该可以正常执行完成,然后开始执行循环,,我上面说了
struct card *card_creactlist(struct card *player[],int i);
struct card *paixu_list(struct card *player[],int i); 这两条语句是函数声明,,所以,在这里这两条语句不起任何作用,不会产生任何可执行代码,跳过,继续执行
for(head=player[i];....i首先为0,player[0]就算你初始化成功了,它也是player1的值,而player1在定义后并未初始化就用它给player[]进行初始化了,全局变量默认为0,,所以player[0]的值是0,也就是NULL(当然这些都是在你初始化正确执行的情况下,事实上,全局变量初始化根本不会正确执行)....继续执行
判断循环条件,head->next,,,head刚用player[0]赋值成了NULL,你现在就用head->next,显然引用了一个不可以被引用的内存,,段错误在这里就产生了,,,
再说明白点,你这么长个代码,除了对一个数组进行了赋值外,其它什么也没干就产生段错误了