【问题标题】:c array malloc unknown sizec数组malloc未知大小
【发布时间】:2014-09-14 04:18:46
【问题描述】:

在处理输入文件之前,如何在不知道有多少字符串的情况下创建唯一字符串数组?最多可以有 200 万个字符串,最大长度为 50。 我的程序是这样的。这适用于 51 个项目,然后覆盖其他数据。如果可能的话,我不知道如何向数组中添加元素。

main() {

    char *DB_NAMES[51]; // i thought this gave me ptrs to chunks of 51
                // but it's 51 pointers!
    char *word;

    while not eof {
        ...function to read big string 
        ...function to separate big sting into words
        ...
        processWord(ctr, DB_NAMES, word);
        ...
    }
}

processWord(int ndx, char *array1[], char *word){

    ...function to find if word already exists...

    //if word is new, store in array 
        array1[ndx]= (char *)malloc(sizeof(51)); // isn't this giving me a char[51]?    
        strcpy(array1[ndx],word);
    ...
}

【问题讨论】:

  • C 中没有未知大小的数组。您必须编写自己的数据结构,如链表。
  • array1[ndx]= (char *)malloc(sizeof(51)); 是的,这将为 array1[] 分配 51 个字节的内存,但我认为大小是 ndx 的值

标签: c arrays pointers malloc


【解决方案1】:

您可以首先使用以下逻辑获取文件中的字数,当您获得文件中的字数时,您可以使用字数初始化数组大小。

#include<stdio.h>
#define FILE_READ "file.txt"

int main()

{
    FILE * filp;
    int count = 1;
    char c;
    filp = fopen(FILE_READ, "r");
    if(filp == NULL)
        printf("file not found\n");
    while((c = fgetc(filp)) != EOF) {
        if(c == ' ')
            count++;
    }
    printf("worrds = %d\n", count);
    return 0;
}

问候, yivx

【讨论】:

  • 我做了一个分析,我需要 250 万字。当我尝试分配它时,我的程序崩溃了,尽管我有足够的内存。我需要学习记忆。
【解决方案2】:

最好不要使用固定的字符串长度;节省内存空间。

    char **DB_NAMES = 0;    // pointer to first char * ("string") in array; initially 0

通过引用传递指针,以便可以更改它。此外,您还需要新的 ctr 值,以防存储了新单词。

        ctr = processWord(ctr, &DB_NAMES, word);

相应地更改函数processWord。

int processWord(int ndx, char ***array1a, char *word)
{   char **array1 = *array1a;
    ...function to find if word already exists...

    // if word is new, store in array
    {
        array1 = realloc(array1, (ndx+1)*sizeof*array1);    // one more string
        if (!array1) exit(1);                               // out of memory
        array1[ndx++] = strdup(word);                       // store word's copy
        *array1a = array1;                                  // return new array
    }
    return ndx;                                             // return count
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-13
    • 2016-05-07
    • 1970-01-01
    • 2016-03-03
    • 2014-02-22
    • 2015-04-29
    相关资源
    最近更新 更多