2013-03-21 36 views
1

在程序的二维阵列,我已经从输入动态分配两个固定长度字符串

scanf("%s",currWord); 

词语,其中进来的线的非限定数目的非限定数进行扫描。

我想把这些单词放在一个2维的字符串数组中。字符串的长度 固定[MAX_WORD_LEN+1]

我的想法是:

int row=10 //10 lines for starting 
int col=5 //5 words in each line for starting 
int i; 

typedef char word[MAX_WORD_LEN+1]; //new type of 11char lenght string 
word** matrix; //2 dimensional array (pointers) with no memory 

matrix = malloc(row*sizeof(word*)); //allocate row number of word* (word pointer) size 

for(i=0;i<row;i++) 
{ 
    matrix[i] = malloc(col*sizeof(word)); //allocate col number of words to each row 
} 

所以,我不知道如果这是正确的。

我会很乐意为一些帮助和提示..

编辑:

当接收到来自输入我不得不增加内存(行的字数每一行)若言需要,我该怎么做? (?realloc的)

我需要做到以下几点:

Image

+3

[有没有我们在这里之前](http://stackoverflow.com/questions/15526642/dynamic-allocation-of-an-array-of-strings-in-c)? – WhozCraig 2013-03-21 07:54:14

+0

尽管这属于codereview,但如果您的意图是[MAX_WORD_LEN + 1]大小的char缓冲区网格,它看起来是正确的。您可能想要检查malloc返回值等。我不得不问,最终的目标是从输入中得到单词的二维布局,并按照每行文字的动态列表进行排列? – WhozCraig 2013-03-21 07:59:18

+1

你的变量名称导致了所有这些混淆恕我直言。考虑这个:'typedef char ** matrix',然后声明你的二维数组如:'matrix wordList'并继续。 – 2013-03-21 08:04:07

回答

1

没有进入细节,最简单的方法是使用一个矩阵作为链表的链表..

struct matrix_field 
{ 
    char data [11]; 
    matrix_field * next_field; 
}; 

struct matrix_row 
{ 
    matrix_field * first_field; 
    matrix_row * next_row; 
}; 

struct matrix 
{ 
    matrix_node * first_row; 
}; 

你的数据会看起来像这样的记忆..

[+] 
| 
v 
[x]-->[a]-->[b]-->[c]--> 
| 
v 
[y]-->[d]-->[e]-->[f]--> 
| 
v 
[z]-->[g]-->[h]-->[i]--> 
| 
v 

--------------- 

[+] matrix 

[x] .. [z] matrix_row 

[a] .. [i] matrix_field 
相关问题