看板 C_and_CPP 關於我們 聯絡資訊
#include <stdio.h> #include <stdlib.h> int main() { int i,j; char k[10]; char **ptr = (char **) malloc(2 * sizeof(char *)); for (i=0;i<3;i++) { ptr[i]=(char*)malloc(3 * sizeof(char)); } //---------------以上適配置二為記憶體-----------------------// for(int i=0;i<2;i++) { for(int j=0;j<3;j++) { printf("Enter string\n"); fgets(k,1000,stdin); ptr[i][j]=*k; printf("ptr[%d][%d] is %s\n", i,j ,*k); } } for(int x=0;x<2;x++) { for(int y=0;y<3;y++) { printf("ptr[%d][%d]=%s\n", i , j , ptr[x][y]); } } //回收ptr陣列的第二維記憶體 for (i=0;i<2;i++) { free(ptr[i]); } free(ptr); //回收ptr陣列的第一維記憶體 system("pause"); return 0; } 請問我建立了一個二維的動態陣列2*3我想要手動輸入 六個字串 但是程式執行結果錯誤一堆 請問我該怎麼樣改這個程式讓他可以 在六個格子裡面手動輸入六個字串 我需要改成3維動態陣列嗎???? 開發平台(Platform): (Ex: VC++, GCC, Linux, ...) 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 餵入的資料(Input): 預期的正確結果(Expected Output): 錯誤結果(Wrong Output): 程式碼(Code):(請善用置底文網頁, 記得排版) 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 122.116.220.174 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1474780808.A.F65.html
ilikekotomi: printf用了%s應該是會印到陣列出現\0 09/25 13:35
ilikekotomi: 雖然不知道原本用途 但改用%c應該比較符合你的邏輯 09/25 13:37
EdisonX: 應該會先 crash ?? 第一個 for 應該到 2 09/25 13:40
ilikekotomi: 搞錯你意思 原來是要6個字串 09/25 13:41
ilikekotomi: 由於每次你都是存到k這個陣列 所以會錯掉 09/25 13:43
ilikekotomi: 如果你印是要用陣列的話卻時要3維沒錯 09/25 13:44
ilikekotomi: 然後prt[i][j] = (char*)malloc(10*sizeof(char)) 09/25 13:45
ilikekotomi: 將ptr[i][j]初始化後 用strcpy從k複製到ptr[i][j] 09/25 13:47
ilikekotomi: 但建議你不要用到那麼多 或是改用C++的string 09/25 13:48
ilikekotomi: 應該是沒什麼必要弄成2*3陣列的字串才對 09/25 13:48
ilikekotomi: 建議你進一步釐清pointer和字串的觀念來寫會比較好 09/25 13:49
pttworld: 1000和3的關係是。。? 09/25 14:23