1. 程式人生 > 其它 >C++之我的錯誤篇(一)

C++之我的錯誤篇(一)

問題描述:在列印陣列時,前面的數字成功列印,後面的出現錯誤(打印出地址來)

程式碼如下:

#include <iostream>
#include "malloc.h"
#include "stdlib.h"
#define OK 1
#define OVERFLOW -1
#define ERROR 0
#define QMAXSIZE 23//定義長度,長度>=輸出行數+3
typedef int ElemType;
typedef int Status;

using namespace std;

typedef struct
{
    ElemType   *base
; //初始化的動態分配儲存空間 int f_ront; //頭指標,佇列不空指向佇列頭元素 int rear; //尾指標,佇列不空指向佇列尾元素下一位置 }SqQueue; Status InitQueue(SqQueue &Q) {//構造空佇列 Q.base = new ElemType[QMAXSIZE]; if (!Q.base) exit (OVERFLOW); Q.f_ront=Q.rear=0; return OK; } ElemType QueueLength(SqQueue Q) {//獲取佇列長度 return
(Q.rear-Q.f_ront+QMAXSIZE)%QMAXSIZE; } void GetHead(SqQueue Q,ElemType &e) {//返回隊頭元素 if(Q.f_ront == Q.rear) e=0; else e=Q.base[Q.f_ront]; } Status EnQueue(SqQueue &Q,ElemType e) {//插入元素 if((Q.rear+1)%QMAXSIZE==Q.f_ront) return ERROR; Q.base[Q.rear]=e; Q.rear
=(Q.rear+1)%QMAXSIZE; return OK; } Status DeQueue(SqQueue &Q,ElemType &e) {//刪除元素 if(Q.f_ront==Q.rear) return ERROR; e=Q.base[Q.f_ront]; Q.f_ront=(Q.f_ront+1)%QMAXSIZE; return OK; } Status QueueEmpty(SqQueue &Q) {//判斷佇列是否為空 if(Q.f_ront==Q.rear) return OK; else return ERROR; } void PrintQueue(SqQueue Q, ElemType n) {//遍歷迴圈佇列,並列印所有元素 cout<<""<<n<<"行:"; ElemType x=Q.f_ront%QMAXSIZE; while(x%QMAXSIZE!=Q.rear){ cout<<Q.base[x]<<"\t"; x++; //更正後為x=(x+1)/QMAXSIZE } } void YangHui(int n) {//楊輝三角 SqQueue Q; ElemType j,s,t; printf("第1行:1\n"); InitQueue(Q); EnQueue(Q,0); /*開始*/ EnQueue(Q,1); /*第1行*/ EnQueue(Q,1); for(j=2;j<n;j++) //從第二行開始迴圈到n-1行 { EnQueue(Q, 0); /*第j行的結束符*/ printf("第%d行:",j); do { DeQueue(Q,s); GetHead(Q,t); if(t) printf("%d\t",t); /*非0輸出,否則換行*/ else printf("\n"); EnQueue(Q,s+t); } while(t!=0); /*遇到結束符前迴圈*/ } DeQueue(Q,s); //輸出最後一行 PrintQueue(Q,j); } main() { ElemType n; while(true) { printf("請輸入輸出的行數(小於等於%d):",QMAXSIZE-3); scanf("%d",&n); if(n<=(QMAXSIZE-3)&&n>1) { YangHui(n); break; } else printf("輸入錯誤,請重新輸入\n"); } }

由於是在最後一行輸出出現問題,我便開始檢查輸出最後一行的程式碼,但是看來看去就沒錯。最後設定斷點除錯,發現到後面,Q.base[QMAXSIZE]陣列已經越界,QMAXSIZE=23。所以造成Q.base的值輸出是一個結果。

將x++改成x=(x+1)/QMAXSIZE後輸出正確

新手,歡迎大家指正