如何在C中动态分配字符串数组? [英] How to dynamically allocate an array of strings in C?

查看:134
本文介绍了如何在C中动态分配字符串数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个noob,所以不要很难。

I'm a noob so don't be hard on be.

而不是这样的东西;

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

是否可以动态分配数组中有多少字符串与malloc,就像动态为char指针分配内存这样的东西:

Is it possible to dynamically allocate how many strings will be in the array with malloc just like when you dynamically allocate memory for char pointer? Something like this:

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

我尝试过但不起作用;必须有一些我在做错事。
我想到的其他解决方案是:

I tried it but it doesn't work; There must be something I'm doing wrong. The other solution I thought of was:

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

但是我想知道是否可以使用malloc。

but I want to know if that's possible using malloc.

推荐答案

您也可以使用 malloc 为每个单词,像这样

You can also use malloc for each word, like this

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] 是表示您希望数组包含的字符串数的整数, i th数组中的字符串。

where numberOfStrings and lengthOfStrings[i] are integers that represent the number of strings you want the array to contain, an the length of the ith string in the array respectively.

这篇关于如何在C中动态分配字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆