C++,而(P!= NULL)不工作
问题描述:
this is the code source of my programC++,而(P!= NULL)不工作
我在与while循环的问题//而(P!= NULL) 它不工作每当执行reachs循环程序停止工作!尽管P已经初始化,并且p在循环之后不被使用!
void Ajout_Debut() {
Q=(Liste*) malloc(sizeof(Liste));
Liste *Q=new Liste();
cout<<"donnez cod_prod"<<endl;
cin>>cp;
cout<<"donnez designation"<<endl;
cin>>ds;
cout<<"donnez unite de mesure"<<endl;
cin>>u;
cout<<"donnez prix unitaire d'achat hors taxe'"<<endl;
cin>>pu;
cout<<"donnez la quantite achetee"<<endl;
cin>>qt;
cout<<"donnez tva (9 ou bien 21)"<<endl;
cin>>tv;
Q->cod_prd=cp;
Q->dsg=ds;
Q->tva=tv;
Q->um=u;
Q->pua=pu;
Q->qte=qt;
if(Tete!= NULL) {
Q->svt=Tete;
Tete=Q;
}
else {
Tete=Q;
Tete->svt==NULL;
free(Q);
}}
void Afficher() {
P=Tete;
int a=1;
if(P==NULL)
cout<<"La liste est vide !"<<endl;
while(P!=NULL) {
cout<<P->cod_prd<<endl;
cout<<P->dsg<<endl;
cout<<P->um<<endl;
cout<<P->pua<<endl;
cout<<P->qte<<endl;
cout<<P->tva<<endl;
P=P->svt;
}
}
int main() {
Tete=NULL;
int c;
string cp;
do {
cout<<"\001 \001"<<endl;
cout<<"\001 01-Ajouter un produit au debut \001"<<endl;
cout<<"\001 02-Suprimer un produit \001"<<endl;
cout<<"\001 03-Afficher la liste des produit achetes \001"<<endl;
cout<<"\001 04-Afficher le nombre total des produits achetes \001"<<endl;
cout<<"\001 05-afficher le montants total HT \001"<<endl;
cout<<"\001 06-afficher le montants total TVA \001"<<endl;
cout<<"\001 07-afficher le montants total TTC (Net à Payé) \001"<<endl;
cout<<"\001 08-demander au client le paiement et calculer la difference \001"<<endl;
cout<<"\001 09-afficher le prix max et le prix min \001"<<endl;
cout<<"\001 10-Vider la liste \001"<<endl;
cout<<"\001 00-quitter \001"<<endl;
cout<<"\001 \001"<<endl;
cout<<" Votre Choix:";
cin>>c;
if(c<0 || c>10) {
cout<<"Votre choix n'existe pas ! "<<endl;
}
if (c>0 && c<11) {
switch(c) {
case 1 :
Ajout_Debut();break;
case 2 :
Supprimer();break;
case 3 :
Afficher();break;
case 4 :
CalAffi (4);break;
case 5 :
CalAffi (5);break;
case 6 :
CalAffi (6);break;
case 7 :
CalAffi (7);break;
case 8 :
Payment();break;
case 9 :
MaxMin();break;
case 10:
Vider();break;
}}}while(c!=0); if (c==0) system("PAUSE");}
AND here is a photo of what happens when i call the afficher function 由我使用的功能ajout_debut afficher beforecaliing的方式,使已经存在的列表
答
这里的元素是非常大问题:
Tete=Q;
Tete->svt==NULL;
free(Q);
首先你使Tete
指向与Q
指向的内存相同的内存。这意味着Tete
和Q
指向相同的内存。
那么几行后,你释放该都Q
和Tete
指向的内存。这意味着在此之后的所有解除引用Tete
是无效的,并将导致undefined behavior。
此外,使用Tete->svt==NULL;
您不会将NULL
分配给“下一个”指针svt
。你比较它到NULL
然后丢弃结果。
欢迎来到*.com。请花些时间阅读[帮助页面](http://*.com/help),尤其是名为[“我可以问些什么话题?”](http://*.com/help/讨论话题)和[“我应该避免问什么类型的问题?”](http://*.com/help/dont-ask)。还请[参观](http://*.com/tour)和[阅读如何提出好问题](http://*.com/help/how-to-ask)。最后,请学习如何创建[最小,完整和可验证示例](http://*.com/help/mcve)。 –
请提供您的代码样本。 – jeteon
该代码中有很多P!= NULL的地方。 –