[問題] 用指標建陣列的問題

看板C_and_CPP作者 (幻想的夢境)時間13年前 (2011/03/27 01:40), 編輯推噓0(005)
留言5則, 3人參與, 最新討論串1/3 (看更多)
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) VC++ 2008 問題(Question): 取100個亂數放入陣列(用指標+MALLOC),印出這100個亂數並排序 預期的正確結果(Expected Output): 會出現200個數字,前100個是未排序,後100個是排序好的 錯誤結果(Wrong Output): 執行到第7個的時候VC++就跟我說發生例外狀況...我按繼續它就給我停掉了= = 如果執行7個以下都不會..... 程式碼(Code):(請善用置底文網頁, 記得排版) #include<stdlib.h> #include<stdio.h> #include<malloc.h> #define swap(a,b,t) ((t=a),(a=b),(b=t)) #define max 100 void main(){ int *a,i,j,t; for(i=0;i<max;i++){ a=(int *)malloc(sizeof(a)); a[i]=rand()%223+123; printf("%d ",a[i]); } for(i=0;i<max;i++){ for(j=i;j<max;j++){ if(a[j]<=a[i]) swap(a[i],a[j],t); } } printf("\n"); for(i=0;i<max;i++){ printf("%d ",a[i]); } system("pause"); } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 123.192.75.67 ※ 編輯: jacky1989 來自: 123.192.75.67 (03/27 01:40)

03/27 01:53, , 1F
http://pastie.org/1718774 先把malloc改一下
03/27 01:53, 1F

03/27 01:56, , 2F
咦?對了耶...不過我的問題是出在哪?還是不太懂= =可是排
03/27 01:56, 2F

03/27 01:56, , 3F
序那邊還是有錯= =
03/27 01:56, 3F
呵呵~不好意思是我放錯邊了,排序那邊也對了....可是能跟我說我的問題到底在哪嗎? ※ 編輯: jacky1989 來自: 123.192.75.67 (03/27 01:58)

03/27 01:58, , 4F
a=(int*)malloc(sizeof(int)*max); 沒有*max 塞不下吧
03/27 01:58, 4F

03/27 01:59, , 5F
我想我理解了...謝謝各位
03/27 01:59, 5F
文章代碼(AID): #1DZYJt2L (C_and_CPP)
文章代碼(AID): #1DZYJt2L (C_and_CPP)