我有以下结构
struct jucator{
char nume[100];
int *salariu;
struct jucator *urm;
};
struct echipa{
char nume[100];
struct jucator *jc;
struct echipa *urm;
};
struct echipa *ech;
void adaugajuc(char nume[100],char echipa[100],int salariu)
{
struct echipa *e=ech;
while(e)
{
if(strcmp(e->nume,echipa)==0) break;
e=e->urm;
}
if(e->jc==NULL)
{
e->jc=(struct jucator *)malloc(sizeof(struct jucator *));
*(e->jc->salariu)=salariu;
e->jc->urm=NULL;
strcpy(e->jc->nume,nume);
}
else{
struct jucator *jc=e->jc;
while(jc->urm&&jc->urm->salariu>salariu) jc=jc->urm;
if(jc==e->jc&&jc->salariu<salariu)
{
struct jucator *nod=(struct jucator *)malloc(sizeof(struct jucator *));
*(nod->salariu)=salariu;
nod->urm=jc;
strcpy(nod->nume,nume);
e->jc=nod;
}
else{
if(jc!=e->jc&&!jc->urm&&jc->salariu>salariu)
{
struct jucator *nod=(struct jucator *)malloc(sizeof(struct jucator *));
*(nod->salariu)=salariu;
nod->urm=NULL;
strcpy(nod->nume,nume);
jc->urm=nod;
}
else{
struct jucator *nod=(struct jucator *)malloc(sizeof(struct jucator *));
*(nod->salariu)=salariu;
nod->urm=jc->urm;
jc->urm=nod;
strcpy(nod->nume,nume);
}
}
}
}
我在函数中添加了元素。问题是,如果我不将
*salariu
放在第一个结构中,而仅将salariu
放在salariu
中,则会有一个具有奇怪值的元素。我的问题是为什么?
我指定每个变量都是global。
我根据
salariu
降序排列它们。请也说明一下,为什么它如此工作,并且没有指针,我却得到奇怪的值(并非总是如此)。
最佳答案
salariu
是指向int
的指针:
struct jucator{
char nume[100];
int *salariu;
struct jucator *urm;
};
但是,您要在以下位置分配普通的
int
而不进行解引用(也没有用于存储值的空间):void adaugajuc(char nume[100],char echipa[100],int salariu)
{
struct echipa *e=ech;
while(e)
{
if(strcmp(e->nume,echipa)==0) break;
e=e->urm;
}
if(e->jc==NULL)
{
e->jc=(struct jucator *)malloc(sizeof(struct jucator *));
e->jc->salariu=salariu; /*HERE */
和这里:
demo.c:42:36: warning: comparison between pointer and integer
while(jc->urm&&jc->urm->salariu>salariu) jc=jc->urm;
^
demo.c:44:30: warning: comparison between pointer and integer
if(jc==e->jc&&jc->salariu<salariu)
^
demo.c:48:21: warning: assignment makes pointer from integer without a cast
nod->salariu=salariu;
^
demo.c:55:44: warning: comparison between pointer and integer
if(jc!=e->jc&&!jc->urm&&jc->salariu>salariu)
您可以解决以下问题:
e->jc->salariu = malloc(sizeof(int)); /* Reseve space for the int */
*(e->jc->salariu)=salariu;
或者更好的是,在
int
中使用普通的struct
:struct jucator{
char nume[100];
int salariu;
struct jucator *urm;
};