如何动态分配一系列行 C?

我很好,所以对他来说并不严格。

而不是这样的东西;


char string[NUM OF STRINGS][NUM OF LETTERS];


是否可以动态分配数组中的数量有多少行 malloc, 就像当指针的动态内存分配一样 char? 类似的东西:


int lines;
scanf/"%d", &lines/;
char *string[NUM OF LETTERS]
string = malloc/sizeof/char/ * lines/;


我试过,但它没有工作; 我一定有什么问题。
我想到的另一个决定是:


int lines;
scanf/"%d", &lines/;
char string[lines][NUM OF LETTERS];


但我想知道是否有可能 malloc.
已邀请:

八刀丁二

赞同来自:

你也可以使用
malloc

例如,对于每个单词


char **array;
int lines;
int i;

while /scanf/"%d", &lines/ != 1/;

array = malloc/lines * sizeof/char *//;
if /array != NULL/
{
for /i = 0 ; i < lines ; ++i/
{
int numberOfLetters;

while /scanf/"%d", &numberOfLetters/ != 1/;
array[i] = malloc/numberOfLetters/;
}
}


在哪里
numberOfStrings


lengthOfStrings[i]

-open表示要包含在数组和长度中的行数
i

- 分别在阵列中的行。

龙天

赞同来自:

你有两种方法可以实现它。

第一个是更复杂的,因为它需要对字符串数组的内存分配,以及每行的内存分配。

您可以为整个数组选择内存:


char /*array/[NUM_OF_LETTERS]; // Pointer to char's array with size NUM_OF_LETTERS
scanf/"%d", &lines/;
array = malloc/lines * NUM_OF_LETTERS/;
. . .
array[0] = "First string\n";
array[1] = "Second string\n";
// And so on;


第二种方法的缺点是它被分配的每一行
NUM_OF_LETTERS

字节。 因此,如果您有很多短线,则第一种方法会更好。

喜特乐

赞同来自:

如果您需要持续的内存分配:


char **string = malloc/nlines * sizeof/char *//;
string[0] = malloc/nlines * nletters/;
for/i = 1; i < nlines; i++/
string[i] = string[0] + i * nletters;


有关更详细的解释:阅读
http://www.c-faq.com/aryptr/dynmuldimary.html
.

涵秋

赞同来自:

int lines;
scanf/"%d", &lines/;
char /*string/[NUM OF LETTERS]
string = malloc/sizeof/*string/ * lines/;

冰洋

赞同来自:

[code]char **ptop;
int iStud;
int i;
printf/"Enter No. of Students: "/;
scanf/"%d",&iStud/;

ptop=/char **/ malloc/sizeof/char/*iStud/;
flushall//;


for/i=0;i<istud;i++ *="" *50="" ;="" ;[="" <="" char="" code]="" div="" for="" free="" gets="" i="0;i&lt;iStud;i++/" malloc="" ptop="" ptop[i]="" puts="" sizeof="" {="" }="">
</istud;i++>

要回复问题请先登录注册