[爆卦]Malloc 多維 陣列是什麼?優點缺點精華區懶人包

為什麼這篇Malloc 多維 陣列鄉民發文收入到精華區:因為在Malloc 多維 陣列這個討論話題中,有許多相關的文章在討論,這篇最有參考價值!作者stanley0412 (逐夢)看板C_and_CPP標題[問題] 讀檔跟三維動態陣列時間Thu...


開發平台(Platform): (Ex: VC++, GCC, Linux, ...)

Dev C++

問題(Question):

讀TXT檔少讀半格,冏!!

三維陣列讀檔那邊,印出來確實是六次,每次顯示的數值也不一樣,
但最後印出來的全都一樣..不知道是哪裡有問題..

餵入的資料(Input):

123 integer
234 string
532 float

預期的正確結果(Expected Output):

印在螢幕上的是

the element of data[0][0] is 123
the element of data[0][1] is integer
the element of data[1][0] is 234
the element of data[1][1] is string
the element of data[2][0] is 532
the element of data[2][1] is float
123 integer
234 string
532 float

錯誤結果(Wrong Output):

the element of data[0][0] is 23
the element of data[0][1] is integer
the element of data[1][0] is 234
the element of data[1][1] is string
the element of data[2][0] is 532
the element of data[2][1] is float
float float
float float
float float

程式碼(Code):(請善用置底文網頁, 記得排版)

讀檔與動態陣列的部分:

FILE *fptr;
fptr = fopen("test.txt","r");
if(fptr==NULL)
cout<<"error opening file\n";
char ***data = new char **[3];
for(int i = 0;i<3;i++){
data[i] = new char *[2];
for(int j = 0;j<2;j++)
data[i][j] = (char*)malloc(sizeof(char));
}

把檔案的東西塞入陣列裡:

char ch;
char str[1000];
int x = 0;
int y = 0;
while((ch=getc(fptr))!=EOF){
fscanf(fptr,"%s",str);
int j = strlen(str);
if(j!=0){
data[x][y] = str;
cout<<"the element of data["<<x<<"]["<<y<<"] is "<<data[x][y]<<endl;
y++;
if(y==2){
x++;
y=0;
}
}
if(x==3)
break;
}

顯示出來的部分:

for(int x = 0;x<3;x++){
for(int y = 0;y<2;y++){
cout<<data[x][y]<<" ";
}
cout<<endl;
}

補充說明(Supplement):

只是想寫個小程式測試小文件看看,所以才會把行、列寫死
TXT檔的編碼都試過了0.0a 還是不行Orz

--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.109.196.209
※ 編輯: stanley0412 來自: 140.109.196.209 (09/29 12:01)
shadow0326:你所有的data[x][y]都指向str 但是str的值會不斷改變 09/29 12:03
shadow0326:至於檔案中第一個1被getc吃掉了 09/29 12:04
shadow0326:我個人是建議 與其用多維陣列把自己搞亂 不如用class 09/29 12:05
priv:c string的觀念錯誤,回去查一下吧 09/29 12:19
priv:還有那行malloc是幹嘛的… 09/29 12:20
priv:再來,要寫c就寫c,要寫c++就c++,不要new和malloc混用 09/29 12:23
priv:stdio style和iostream style混用看了也很難過 09/29 12:25
priv:初學儘量不要東抄一點西抄一點 09/29 12:25
stanley0412:我還真不太了解malloc是幹嘛的= = 09/29 12:34
stanley0412:改看看好了 謝謝O_Q 09/29 12:35
priv:如果要寫C式的話,string等於字元陳列,不能這樣用等於的 09/29 12:39
priv:如果要寫C++式的話,不要搞這種三維陣列 09/29 12:40
priv:然後用string class而不要用char* 09/29 12:40
stanley0412:好~ 謝謝~ 09/29 13:46
stanley0412:網路上東找西找還真的蠻雜的 回去翻書好了= = 09/29 14:00
lwecloud:malloc那段是從另一個地方抄進來的吧?XD 09/29 15:00
stanley0412:對阿XD 09/29 15:47
stanley0412:東西都蠻模糊的= = 09/29 15:50

你可能也想看看

搜尋相關網站