2015-01-09 54 views
1

我的代碼:如何添加字符到二維數組?

FILE * file; 

file = fopen("c://catalog//file.txt", "r"); 
int m,n; //size of 2d array (m x n) 
fscanf(file, "%d", &m); 
fscanf(file, "%d", &n); 
fclose(file); 

printf("Size: %d x %d\n", m, n); 

// create 2d array 
char **TAB2 = new char*[m]; 
for (int i = 0; i < m; i++) 
    char *TAB2 = new char[n]; 

// display 2d array 
for (int i = 0; i < m; i++){ 
    for (int j = 0; j < n; j++) 
    { 
     printf("%c ", &TAB2[i][j]); 
    } 
    printf("\n"); 
} 

如何填補這個數組與字符或字符串?例如文本= 「成才」,而對於3×5陣列將是:

S o m e t 
h i n g ? 
? ? ? ? ? 

我嘗試:TAB2 [0] [0] = 'S'; * & TAB2 [0] [0] ='s';對於一個字符,這一點兒也不工作...

也許我不好使用指針(?)。任何人都幫助我?

+1

什麼是'plik'? – haccks

+0

我更正了,這應該是'文件' – adfgvx

+0

指針的不良使用是*在這裏使用*它們。 –

回答

2

動態分配陣列是錯誤的。

char **TAB2 = new char*[m]; 
for (int i = 0; i < m; ++i) 
    TAB2[i] = new char[n]; 

請檢查此link尋求幫助。


你可以試試這個:

#include<iostream> 
using namespace std; 

int main() { 

    const int m = 3, n = 5; 
    char **TAB2 = new char*[m]; 
    for (int i = 0; i < m; ++i) 
     TAB2[i] = new char[n]; 

    char c; 
    for (int i = 0; i < m; ++i) { 
    for (int j = 0; j < n; ++j) { 
     std::cin >> c; 
     TAB2[i][j] = c; 
    } 
    } 

    for (int i = 0; i < m; ++i) { 
    for (int j = 0; j < n; ++j) { 
     std::cout << TAB2[i][j]; 
    } 
    std::cout << "\n"; 
    } 

    // NEVER FORGET TO FREE YOUR DYNAMIC MEMORY 
    for(int i = 0; i < m; ++i) 
    delete [] TAB2[i]; 
    delete [] TAB2; 

    return 0; 
} 

輸出:

jorje 
georg 
klouv 
jorje 
georg 
klouv 

重要環節:

  1. How do I declare a 2d array in C++ using new?
  2. How do I use arrays in C++?
+0

http://stackoverflow.com/questions/936687/how-do-i-declare-a-2d-array-in-c-using-new/936702#936702或http://stackoverflow.com/questions/ 4810664/how-do-i-use-arrays-in-c – sehe

+0

哦,這裏是我的圖片在第一個鏈接@sehe!哈哈。順便說一句,好的鏈接,我正在編輯。 – gsamaras

+0

謝謝@ G.Samaras – adfgvx

2

陣列的分配不正確似乎;它應該如下。

char **TAB2 = new char*[m]; 
for (int i = 0; i < m; i++) 
    TAB2[i] = new char[n];