2011-02-05 33 views
1

這個想法是從標準輸入讀取字符串直到到達EOF(以這種格式"string - string")。然後,將該字符串分解爲兩個字符串,並將它們保存到2d數組中。該數組是動態分配最初2行和20列,但我想添加2個額外的行,每次我想添加下一個字符串(功能expandmat())。這裏是我的代碼:C將字符串保存到2d陣列

char ** alloc(int rows, int collums) { 
    char ** mat; 
    int i; 
    mat = malloc(sizeof (char *) * rows); 
    for (i = 0; i < rows; i++) { 
     mat[i] = malloc(sizeof (char) * collums); 
    } 
    return mat; 
} 

char ** addtoarray(char ** mat, char * string1, char * string2, int position) { 

    sscanf(string1, "%s", mat[positon]); 
    sscanf(string2, "%s", mat[positon+1]); 
    return mat; 
} 

char ** getinput(char * longstring, char * string1, char * string2) { 

    int position = 0, n = 2, max = 30; 
    char ** mat; 
    mat = alloc(n, max); 
    while (fgets(longstring, max, stdin)) { 
     sscanf(longstring, "%s - %s", string1, string2); 
     addtoarray(mat, string1, string2, positon); 
     n += 2; 
     position += 2; 
     mat = expandmat(mat, n); 
    } 

    return mat; 
} 

而且,如果有一些在此代碼,這並不讓任何意義,你能告訴我如何解決它?

我知道這似乎是一個微不足道的任務,但它一直讓我發瘋。

感謝您的幫助。

+0

原諒我這個評論,但是這就是爲什麼我喜歡更高級別的妹妹語言如Java或C#在平原C.這是很容易的原因寫在HLL中。 (感謝圖書館。) – 2011-02-05 22:48:04

回答

0

查看realloc C函數來調整mat大小。

expandmat應該realloc的墊子,這樣就可以增加兩個行(它應該返回的矩陣爲好,因爲realloc的必要時將內存複製到新的位置)

+0

是的,我已經嘗試過realloc,但我不能完全弄清楚它究竟是如何工作的。 – boone 2011-02-05 22:47:52

0

哇...第三次,一個像今天這樣的問題出現在今天:-)。

請檢查在這裏我的回答可以幫助你:Array of C structs