gpt4 book ai didi

c - 动态分配固定长度字符串的二维数组

转载 作者:太空宇宙 更新时间:2023-11-04 03:57:00 25 4
gpt4 key购买 nike

在一个程序中,我必须从输入中扫描

scanf("%s",currWord);

未定义数量的单词,出现在未定义数量的行中。

我想把单词放在一个二维字符串数组中。字符串的长度是固定的 [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
}

所以,我不知道这是否正确。

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

编辑:

当从输入中接收到单词时,如果需要,我必须增加内存(行数和每行中的单词数),我该怎么做? (重新分配?)

我需要做以下事情:

Image

最佳答案

无需详细说明,最简单的方法是将矩阵用作链表的链表..

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

关于c - 动态分配固定长度字符串的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15542051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com