C语言数组新增元素时查重函数返回随机值功能异常如何解决?
问题描述
我是编程新手,目前遇到如下问题:我有多段长度为x的数组,需要向数组中添加b个元素,我采用的实现逻辑是将数组长度设为x+b,引导用户输入数值后调用函数校验该值是否已在数组中存在,若存在则要求用户重新输入。但实际运行时搜索函数返回随机数,fRecherche2函数在fAjouter函数外部可以正常运行。
问题复现表现
- 选择't'选项添加元素,输入要添加1个值后,没有弹出输入信息的提示,程序直接自动添加了随机值
- 查重函数返回值为无规律的随机数
相关代码
int fRecherche2 (int ref[],int n,int nref) { int i; for (i=0;i<n;i++) if (ref[i]==nref) return i; return -1; } int fAjouter(int ref[],int qt[],float prix[],int sds[],int n) { int i,prods,nb,code,nref; printf("How many products would you like to add:"); scanf("%d",& prods); fVerifVal(prods); n=NbArticle(); nb=n+prods; for(i=n;i<nb;i++) { printf("Reference: "); scanf("%d", &ref[i]); ref[i]=nref; code=fRecherche2(ref,n,nref); printf("%d\n",code); while(code!=-1) { printf("The reference already exists.\n"); printf("Please try again: "); scanf("%d", &ref[i]); ref[i]=nref; code=fRecherche2(ref,n,nref); printf("%d",code); if(code==-1) break; } fVerif(ref,i); //Checks if the value is bigger than 0 printf("Amount: "); scanf("%d", &qt[i]); fVerif(qt,i); printf("Price: "); scanf("%f", &prix[i]); fVerifReal(prix,i); //Checks if the value is bigger than 0.00 printf("Security threshold: "); scanf("%d", &sds[i]); fVerif(sds,i); } fEnregNombre(nb); //saves my new size in a file code=fEnreg(ref,qt,prix,sds,nb); // saves all my new arrays in a file if(code==-1) return -1; } void fCreerStock (void) { int i,n; printf("Combien d'articles : "); scanf("%d", &n ); while(n<=1) { printf("Il faut au moins 1 article!\n"); printf("Veuillez réesayer: "); scanf("%d",&n); if(n>0) break; } FILE * nombre; nombre=fopen("Nombre_d'article.txt","w"); if (nombre == NULL) { printf("probleme d'ouverture du fichier \n"); exit(1); } fprintf(nombre,"%d",n); fclose(nombre); int ref[n],qt [n], sds [n]; float prix[n]; for (i=0; i<n; i++) { printf("reference %d : ", i); scanf("%d", &ref[i]); fVerif(ref,i); printf("quantité %d : ", i); scanf("%d", &qt[i]); fVerif(qt,i); printf("Prix %d : ", i); scanf("%f", &prix[i]); fVerifReal(prix,i); printf("seuil de sécurité %d : ", i); scanf("%d", &sds[i]); fVerif(sds,i); } FILE * flot; flot=fopen("nom.txt","a"); if (flot == NULL) { printf("Probleme d'ouverture du fichier \n"); exit(1); } for (i=0; i<n; i++) fprintf(flot,"%d\t%d\t%.2f\t%d\n",ref[i],qt[i],prix[i],sds[i]); fclose(flot); } #include <stdio.h> #include "sae.h" void globale (void) { int n; n=NbArticle(); int ref[n],qt[n],sds[n],CodeErr,code,CodeSup; float prix[n]; char choix; CodeErr=fConsulterStock(ref,qt,prix,sds,n); printf("\n\nBienvenue a l'application de gestion de stock 'Xtrachaus'\n\n"); if (CodeErr== -1 || n == -1) printf("!! Vous n'avez pas encore créer de stock veuillez créer un stock avant de faire n'importe quel manipulation !! \n\n"); printf("Créer un stock: 'c'| Afficher le stock: 'o'| Etat du stock: 'e'| Faire le devis d'une commade: 'd'| Récapitulatif des ventes: 'r'| Approvisionnement: 'a'| \nSupprimer un article:'s'| Rechercher un article avec n° ref: 'n'| Modifier l'article :'m'| Ajouter un article: 't'\n\n"); printf("Que voulez vous faire(votre choix): "); scanf("%c%*c", &choix); if (choix =='c') fCreerStock(); if (choix =='o') fAfficherStock(ref,qt,prix,sds,n); if (choix =='e') fEtatStock(ref,qt,prix,sds,n); /*if (choix =='d') fDevis(); if (choix =='r') fVentes();*/ if (choix =='a') { fAfficherStock(ref,qt,prix,sds,n); code=fAppro(ref,qt,prix,sds,n); if(code==-1) printf("Erreur, l'approvisionement ne peut pas s'effectuer.\n"); else printf("Approvisionement éffectué. \n"); printf("\n"); fAfficherStock(ref,qt,prix,sds,n); } if (choix =='s') { CodeSup=fSuppression(ref,qt,prix,sds,n); if(CodeSup!=-1) printf("Suppression éffectué. \n"); else printf("Erreur, la suppression ne peut pas s'effectuer.\n"); } if (choix =='n') { code=fRecherche(ref,n); if (code!=-1) { printf("\nReference:\tQuantite:\tPrix:\tSeuil de securite:\n"); printf("%d\t\t%d\t\t%.2f\t\t%d\n" ,ref[code], qt[code], prix[code], sds[code]); } else printf("La réference n'existe pas\n"); } if (choix =='t') { code==fAjouter(ref,qt,prix,sds,n); if(code==-1) printf("Erreur, l'ajout ne peut pas s'effectuer.\n"); else printf("Ajout éffectué. \n"); } if (choix =='m') { code=fModifier(ref,qt,prix,sds,n); if(code==-1) printf("Erreur, la modification ne peut pas s'effectuer.\n"); else printf("Modification éffectué. \n"); } } int main (void) { globale(); return 0; }
修复方案
1. 修正赋值逻辑错误
fAjouter函数中两处写反了赋值顺序:
原错误代码:
scanf("%d", &ref[i]); ref[i]=nref;
nref是未初始化的局部变量,值是随机的,你需要把用户输入到ref[i]的值赋值给nref用来查重,修改为:
scanf("%d", &ref[i]); nref = ref[i];
两处相同的错误都要修改。
2. 修正函数调用错误
globale函数中调用fAjouter时错误使用了双等号:
原错误代码:
code==fAjouter(ref,qt,prix,sds,n);
双等号是比较运算符,不会执行函数逻辑,修改为赋值运算符:
code = fAjouter(ref,qt,prix,sds,n);
3. 修正数组越界问题
你目前使用的是变长数组,在globale中定义数组的长度是初始读取的n,在fAjouter中直接访问i >=n的下标属于数组越界,会触发未定义行为。建议将数组改为动态内存分配,使用malloc初始化,需要扩容时调用realloc调整数组长度。
4. 优化输入读取逻辑
读取用户选项的代码可以调整为自动跳过空白字符,避免残留换行符导致输入异常:
原代码:
scanf("%c%*c", &choix);
修改为:
scanf(" %c", &choix);
格式符前加空格会自动跳过所有空白字符(包括换行、空格、制表符等)。
内容的提问来源于stack exchange,提问作者Zipen
相关产品推荐
相关产品推荐

