[問題] 大數加法練習 發生寫入位置存取違規

看板C_and_CPP作者 (...)時間10年前 (2014/10/30 22:25), 編輯推噓3(3013)
留言16則, 7人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) VC++ 問題(Question): 各位大大好 我在做大數加法練習時一直無法成功 改了好幾次寫法 可能是觀念不好 一直找不到癥結點 錯誤結果(Wrong Output): 編譯都會過 但在執行時會出現 "寫入位置 0x00000000 時發生存取違規。" 的訊息而導致中斷 程式碼(Code):(請善用置底文網頁, 記得排版) #define L 100 // L是預計相加數字的最大位數 我設100 using namespace std; int input(int* data,char n[]){ //這個函式負責把輸入的字串反過來並存在 int i,l; //矩陣中 l=sizeof(n); memset(data, 0, sizeof(int)*L); for (i=L-1; i>=0; --i){ data[L-i-1]=n[i]-'0';} return 0;} void add(int *A,int *B,int *out){ //將處理好的矩陣相加,進位 int i,carry; //存入out[]裡面 for (i=0;i<L;i++){ out[i]+=A[i]+B[i]+carry; carry=out[i]/10; out[i]=out[i]%10;}} void print(int *out){ //這個函式把out[]反過來從尾端開始輸出 int i,yo; //即是我預期得到的相加結果 for (i=0;i<L-1;i++){ if(out[i]!=0){yo=i;} break;} for (i=L-1;i>=yo;--i){ cout<<out[i];}} int main() { char a[L],b[L]; int *out=NULL;int *big1=NULL;int *big2=NULL; cin>>a>>b; //把我欲相加的兩個大數字以字串方式 //a[],b[] 輸入 input(big1,a); input(big2,b); add(big1,big2,out); //輸入字串轉換並存放在矩陣後相加 print(out); //印出結果 return 0;} 還請各位多多指教~!! 感謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 61.31.160.161 ※ 文章網址: http://www.ptt.cc/bbs/C_and_CPP/M.1414707942.A.CE5.html

10/31 06:31, , 1F
int *big1=NULL?????
10/31 06:31, 1F

10/31 06:56, , 2F
int input(int* data,char n[]) ... return 0; ????
10/31 06:56, 2F

10/31 06:57, , 3F
我不懂你的input的作用 或許是我C不夠熟...
10/31 06:57, 3F

10/31 06:59, , 4F
++
10/31 06:59, 4F

10/31 07:24, , 5F
你的out, big1, big2通通沒有allocate memory啊
10/31 07:24, 5F

10/31 07:25, , 6F
還有sizeof(char [])不會給你字串長度,要用strlen
10/31 07:25, 6F

10/31 12:53, , 7F
存取違規 通常就是因為 你沒配置記憶體給該變數
10/31 12:53, 7F

10/31 12:57, , 8F
好可愛的排版阿....
10/31 12:57, 8F

10/31 14:20, , 9F
你的out是null耶
10/31 14:20, 9F

10/31 18:19, , 10F
感謝樓上幾位 在配置完記憶體跟改用strlen後 不會執
10/31 18:19, 10F

10/31 18:20, , 11F
行中斷 但是輸出的結果都是一堆-5-5-5-5-5-5-5-5-6
10/31 18:20, 11F

10/31 18:21, , 12F
之類的數字 不論我輸入的是甚麼...想不太到哪裡還
10/31 18:21, 12F

10/31 18:21, , 13F
有問題...
10/31 18:21, 13F

11/01 01:53, , 14F
感覺應該跟傳入char後的型態處理有關係...
11/01 01:53, 14F

11/01 01:54, , 15F
在input函式中cout輸入的字串都不是正確的...
11/01 01:54, 15F

11/01 02:49, , 16F
我只看得懂C,看不懂C++......
11/01 02:49, 16F
文章代碼(AID): #1KKhhcpb (C_and_CPP)