带有 char 数组的数组

Array with char arrays

我想用 malloc 创建一个数组,然后为数组的字段分配 fgets 的输出。

char *words;
words = (char *)malloc(lines*sizeof(char));
int k = 0;
words[k] = (char *)malloc(mysize*sizeof(char));

这行不通,我猜是因为缺少指针。我能做什么?

我想用 malloc 创建一个数组,然后将 fgets 的输出分配给数组的字段。 ? 然后希望您应该将 words 声明为双指针或 char 指针数组。

一种方法是,使用 char 指针数组,如下所示。

char *words[lines]; /* array of pointer, lines is nothing but number of line in file */
for(int row = 0;row < lines; row++) {
    /* allocate memory for each line */
    words[row] = malloc(mysize);/* mysize is nothing but lines has max no of char i.e max no of char */
    /* now read from file */
    fgets(word[row],mysize,fp);/* reading from file(fp) & store into word[0],word[1] etc */
}

或者你也可以使用像char **words;这样的双指针。

一旦工作完成,最后不要忘记释放动态分配的内存。