, когда я вставляю новую структуру A с помощью команды «1» (поэтому у меня уже есть одна или несколько структур A, связанных с одной или несколькими struct S), я теряю ссылку предыдущей структуры A на их структуру С. Для exaple:C потерять указатель
команды 1, а затем команду 3: 2014 и команды 4
Выход:
год выпуска: 2014
matricola: 1
прикажет 1, а затем команду 3: 2015 и команда 4
Выход:
год: 2015
matricola: 2
год: 2014
нет S STRUCT
Надеюсь, что пример будет полезно Вот код:
#include <stdio.h>
#include <stdlib.h>
struct S
{
int matr;
struct S* next;
};
struct A
{
int year;
struct A *nextA;
struct S *nextS;
};
int years = 2013;
int matricola=0;
void insA(struct A**T);
void printA(struct A*T);
void insS(struct A **T);
void printS(struct A *T);
int main()
{
struct A *T=NULL;
int cmd,sc=0;
while(1)
{
printf("\n command:");
sc=scanf("%d",&cmd);
while(sc==0)
{
printf("\nerror:");
fflush(stdin);
sc=scanf("%d",&cmd);
}
if(cmd==1)
{
insA(&T);
}
if(cmd==2)
{
printA(T);
}
if(cmd==3)
{
insS(&T);
}
if(cmd==4)
{
printS(T);
}
}
return 0;
}
void insA(struct A**T)
{
struct A *new_p=(struct A*)malloc(sizeof(struct A));
if(new_p==NULL)
{
printf("Errore");
exit(0);
}
years++;
new_p->nextA=NULL;
new_p->nextS=NULL;
if((*T)==NULL)
{
(*T)=new_p;
}
else
{
new_p->nextA=(*T);
(*T)=new_p;
}
new_p->year=years;
}
void printA(struct A *T)
{
struct A *tmp=T;
while(tmp!=NULL)
{
printf("\n%d",tmp->year);
tmp=tmp->nextA;
}
return;
}
void insS(struct A **T)
{
int search,sc=0;
struct S* new_p=(struct S*)malloc(sizeof(struct S));
if(new_p==NULL)
{
printf("error");
exit(0);
}
new_p->next=NULL;
printf("\nyear in which to insert:");
sc=scanf("%4d",&search);
while(sc==0 || search > years || search <= 2013)
{
printf("\nerror:");
fflush(stdin);
sc=scanf("%4d",&search);
}
struct A*tmp=*T;
while(tmp!=NULL)
{
if(tmp->year==search)
{
matricola++;
if(tmp->nextS==NULL)
{
tmp->nextS=new_p;
}
else
{
new_p->next=tmp->nextS;
tmp->nextS=new_p;
}
}
tmp=tmp->nextA;
}
new_p->matr=matricola;
return;
}
void printS(struct A *T)
{
struct A *tmp=T;
struct S *s=tmp->nextS;
while(tmp!=NULL)
{
printf("\nyear:%d",tmp->year);
if(s==NULL)
{
printf("\nno S struct");
return;
}
else
{
while(s!=NULL)
{
printf("\nmatricola:%d",s->matr);
s=s->next;
}
}
tmp=tmp->nextA;
}
}
И это мой первый пост, так что я прошу прощения за ошибки.
Ваш код будет легче читать, если он правильно отступил. У вас есть источник форматирования, который может сделать это за вас? –
Было бы неплохо, если бы вы имели выход if (cmd == 5) (1); 'с надлежащей очисткой от курса. –
Использование 'fflush (stdin)' не рекомендуется, оно предназначено для использования с stdout. – OiciTrap