59

我知道如何创建一个结构数组但具有预定义的大小。但是,有没有办法创建一个动态的结构数组,使数组变得更大?

例如:

    typedef struct
    {
        char *str;
    } words;

    main()
    {
        words x[100]; // I do not want to use this, I want to dynamic increase the size of the array as data comes in.
    }

这可能吗?


我研究过这个:words* array = (words*)malloc(sizeof(words) * 100);

我想摆脱 100 并在数据进入时存储数据。因此,如果有 76 个数据字段进入,我想存储 76 而不是 100。我假设我不知道有多少数据即将到来进入我的程序。在我上面定义的结构中,我可以将第一个“索引”创建为:

    words* array = (words*)malloc(sizeof(words));

但是我想在之后动态地将元素添加到数组中。我希望我足够清楚地描述了问题区域。主要挑战是动态添加第二个字段,至少这是目前的挑战。


但是,我取得了一些进展:

    typedef struct {
        char *str;
    } words;

    // Allocate first string.
    words x = (words) malloc(sizeof(words));
    x[0].str = "john";

    // Allocate second string.
    x=(words*) realloc(x, sizeof(words));
    x[1].FirstName = "bob";

    // printf second string.
    printf("%s", x[1].str); --> This is working, it's printing out bob.

    free(x); // Free up memory.

    printf("%s", x[1].str); --> Not working since its still printing out BOB even though I freed up memory. What is wrong?

我做了一些错误检查,这就是我发现的。如果在我为 x 释放内存之后,我添加以下内容:

    x=NULL;

那么如果我尝试打印 x 我会得到一个我想要的错误。那么是不是免费功能不起作用,至少在我的编译器上?我正在使用开发人员??


谢谢,我现在明白了,原因是:

FirstName 是一个指向 char 数组的指针,它没有被 malloc 分配,只有指针被分配,在你调用 free 之后,它不会擦除内存,它只是将它标记为在堆上可用结束后来写的。- 马特·史密斯

更新

我正在尝试模块化并将我的结构数组的创建放在一个函数中,但似乎没有任何效果。我正在尝试一些非常简单的事情,我不知道还能做什么。它与以前的思路相同,只是另一个函数 loaddata 正在加载数据,并且在我需要进行一些打印的方法之外。我怎样才能让它工作?我的代码如下:

    # include <stdio.h>
    # include <stdlib.h>
    # include <string.h>
    # include <ctype.h>

    typedef struct
    {
        char *str1;
        char *str2;
    } words;

    void LoadData(words *, int *);

    main()
    {
        words *x;
        int num;

        LoadData(&x, &num);

        printf("%s %s", x[0].str1, x[0].str2);
        printf("%s %s", x[1].str1, x[1].str2);

        getch();
    }//

    void LoadData(words *x, int * num)
    {
        x = (words*) malloc(sizeof(words));

        x[0].str1 = "johnnie\0";
        x[0].str2 = "krapson\0";

        x = (words*) realloc(x, sizeof(words)*2);
        x[1].str1 = "bob\0";
        x[1].str2 = "marley\0";

        *num=*num+1;
    }//

这个简单的测试代码崩溃了,我不知道为什么。错误在哪里?

4

10 回答 10

39

您已将其标记为 C++ 和 C。

如果您使用的是 C++,事情会容易得多。标准模板库有一个名为 vector 的模板,它允许您动态构建对象列表。

#include <stdio.h>
#include <vector>

typedef std::vector<char*> words;

int main(int argc, char** argv) {

        words myWords;

        myWords.push_back("Hello");
        myWords.push_back("World");

        words::iterator iter;
        for (iter = myWords.begin(); iter != myWords.end(); ++iter) {
                printf("%s ", *iter);
        }

        return 0;
}

如果您使用的是 C 语言,事情会变得更加困难,是的,malloc、realloc 和 free 是可以帮助您的工具。您可能要考虑使用链表数据结构。这些通常更容易增长,但不便于随机访问。

#include <stdio.h>
#include <stdlib.h>

typedef struct s_words {
        char* str;
        struct s_words* next;
} words;

words* create_words(char* word) {
        words* newWords = malloc(sizeof(words));
        if (NULL != newWords){
                newWords->str = word;
                newWords->next = NULL;
        }
        return newWords;
}

void delete_words(words* oldWords) {
        if (NULL != oldWords->next) {
                delete_words(oldWords->next);
        }
        free(oldWords);
}

words* add_word(words* wordList, char* word) {
        words* newWords = create_words(word);
        if (NULL != newWords) {
                newWords->next = wordList;
        }
        return newWords;
}

int main(int argc, char** argv) {

        words* myWords = create_words("Hello");
        myWords = add_word(myWords, "World");

        words* iter;
        for (iter = myWords; NULL != iter; iter = iter->next) {
                printf("%s ", iter->str);
        }
        delete_words(myWords);
        return 0;
}

哎呀,对不起世界上最长的答案。所以WRT到“不想使用链表评论”:

#include <stdio.h>  
#include <stdlib.h>

typedef struct {
    char** words;
    size_t nWords;
    size_t size;
    size_t block_size;
} word_list;

word_list* create_word_list(size_t block_size) {
    word_list* pWordList = malloc(sizeof(word_list));
    if (NULL != pWordList) {
        pWordList->nWords = 0;
        pWordList->size = block_size;
        pWordList->block_size = block_size;
        pWordList->words = malloc(sizeof(char*)*block_size);
        if (NULL == pWordList->words) {
            free(pWordList);
            return NULL;    
        }
    }
    return pWordList;
}

void delete_word_list(word_list* pWordList) {
    free(pWordList->words);
    free(pWordList);
}

int add_word_to_word_list(word_list* pWordList, char* word) {
    size_t nWords = pWordList->nWords;
    if (nWords >= pWordList->size) {
        size_t newSize = pWordList->size + pWordList->block_size;
        void* newWords = realloc(pWordList->words, sizeof(char*)*newSize); 
        if (NULL == newWords) {
            return 0;
        } else {    
            pWordList->size = newSize;
            pWordList->words = (char**)newWords;
        }

    }

    pWordList->words[nWords] = word;
    ++pWordList->nWords;


    return 1;
}

char** word_list_start(word_list* pWordList) {
        return pWordList->words;
}

char** word_list_end(word_list* pWordList) {
        return &pWordList->words[pWordList->nWords];
}

int main(int argc, char** argv) {

        word_list* myWords = create_word_list(2);
        add_word_to_word_list(myWords, "Hello");
        add_word_to_word_list(myWords, "World");
        add_word_to_word_list(myWords, "Goodbye");

        char** iter;
        for (iter = word_list_start(myWords); iter != word_list_end(myWords); ++iter) {
                printf("%s ", *iter);
        }

        delete_word_list(myWords);

        return 0;
}
于 2008-11-04T05:26:00.580 回答
13

如果要动态分配数组,可以使用mallocfrom stdlib.h

如果要使用words结构分配 100 个元素的数组,请尝试以下操作:

words* array = (words*)malloc(sizeof(words) * 100);

您要分配的内存大小被传入malloc,然后它将返回一个类型为void( void*) 的指针。在大多数情况下,您可能希望将其转换为所需的指针类型,在本例中为words*.

此处使用sizeof关键字来找出words结构的大小,然后将该大小乘以要分配的元素数。

完成后,请务必使用free()释放您使用的堆内存以防止内存泄漏

free(array);

如果你想改变分配数组的大小,你可以尝试realloc像其他人提到的那样使用,但请记住,如果你做很多reallocs 可能最终会导致内存碎片化。如果您想动态调整数组大小以保持程序的低内存占用,最好不要做太多reallocs。

于 2008-11-04T04:55:22.140 回答
6

这看起来像一个学术练习,不幸的是,因为你不能使用 C++,所以它变得更难了。基本上,您必须管理分配的一些开销,并在以后需要调整内存大小时跟踪已分配的内存量。这就是 C++ 标准库的亮点所在。

对于您的示例,以下代码分配内存并稍后调整其大小:

// initial size
int count = 100;
words *testWords = (words*) malloc(count * sizeof(words));
// resize the array
count = 76;
testWords = (words*) realloc(testWords, count* sizeof(words));

请记住,在您的示例中,您只是分配一个指向 char 的指针,您仍然需要分配字符串本身,更重要的是在最后释放它。因此这段代码分配了 100 个指向 char 的指针,然后将其大小调整为 76,但不分配字符串本身。

我怀疑您实际上想要分配与上述非常相似的字符串中的字符数,但是将 word 更改为 char。

编辑:还请记住,创建函数来执行常见任务并强制执行一致性非常有意义,这样您就不会到处复制代码。例如,您可能有 a) 分配结构,b) 为结构分配值,以及 c) 释放结构。所以你可能有:

// Allocate a words struct
words* CreateWords(int size);
// Assign a value
void AssignWord(word* dest, char* str);
// Clear a words structs (and possibly internal storage)
void FreeWords(words* w);

编辑:就调整结构的大小而言,它与调整 char 数组的大小相同。然而不同的是,如果你使结构数组更大,你可能应该将新的数组项初始化为 NULL。同样,如果您使结构数组更小,则需要在删除项目之前进行清理——即在调整结构数组大小之前已分配的空闲项目(并且仅是分配的项目)。这是我建议创建辅助函数来帮助管理它的主要原因。

// Resize words (must know original and new size if shrinking
// if you need to free internal storage first)
void ResizeWords(words* w, size_t oldsize, size_t newsize);
于 2008-11-04T05:53:20.073 回答
3

您的另一个选择是链表。您需要分析您的程序将如何使用数据结构,如果您不需要随机访问,它可能比重新分配更快。

于 2008-11-04T05:08:20.927 回答
2

在 C++ 中,使用向量。它就像一个数组,但您可以轻松添加和删除元素,它会为您分配和释放内存。

我知道问题的标题是 C,但你用 C 和 C++ 标记了你的问题......

于 2008-11-04T05:07:07.560 回答
1

您在上次更新中的代码不应该编译,更不用说运行了。您将 &x 传递给 LoadData。&x 具有 **words 的类型,但 LoadData 需要 words* 。当然,当您在指向堆栈的指针上调用 realloc 时,它会崩溃。

修复它的方法是将 LoadData 更改为接受 words** 。这样摇摆,你实际上可以修改 main() 中的指针。例如, realloc 调用看起来像

*x = (words*) realloc(*x, sizeof(words)*2);

这与“num”中的原则相同,即 int* 而不是 int。

除此之外,您还需要真正弄清楚单词中的字符串是如何存储的。允许将 const 字符串分配给 char *(如 str2 = "marley\0"),但它很少是正确的解决方案,即使在 C 中也是如此。

另一点:除非你真的需要在字符串末尾有两个 0,否则不需要有 "marley\0"。编译器在每个字符串文字的末尾添加 0。

于 2008-11-05T19:18:24.767 回答
1

对于测试代码:如果要修改函数中的指针,则应将“指向指针的指针”传递给函数。更正后的代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

typedef struct
{
    char *str1;
    char *str2;
} words;

void LoadData(words**, int*);

main()
{
    words **x;
    int num;

    LoadData(x, &num);

    printf("%s %s\n", (*x[0]).str1, (*x[0]).str2);
    printf("%s %s\n", (*x[1]).str1, (*x[1]).str2);
}

void LoadData(words **x, int *num)
{
    *x = (words*) malloc(sizeof(words));

    (*x[0]).str1 = "johnnie\0";
    (*x[0]).str2 = "krapson\0";

    *x = (words*) realloc(*x, sizeof(words) * 2);
    (*x[1]).str1 = "bob\0";
    (*x[1]).str2 = "marley\0";

    *num = *num + 1;
}
于 2011-11-04T14:45:59.600 回答
1

每个编码员都需要简化他们的代码以使其易于理解......即使对于初学者也是如此。

因此,如果您了解这些概念,那么动态使用的结构数组很容易。

// Dynamically sized array of structures

#include <stdio.h>
#include <stdlib.h>

struct book 
{
    char name[20];
    int p;
};              //Declaring book structure

int main () 
{
    int n, i;      

    struct book *b;     // Initializing pointer to a structure
    scanf ("%d\n", &n);

    b = (struct book *) calloc (n, sizeof (struct book));   //Creating memory for array of structures dynamically

    for (i = 0; i < n; i++)
    {
        scanf ("%s %d\n", (b + i)->name, &(b + i)->p);  //Getting values for array of structures (no error check)
    }          

    for (i = 0; i < n; i++)
    {
        printf ("%s %d\t", (b + i)->name, (b + i)->p);  //Printing values in array of structures
    }

    scanf ("%d\n", &n);     //Get array size to re-allocate    
    b = (struct book *) realloc (b, n * sizeof (struct book));  //change the size of an array using realloc function
    printf ("\n");

    for (i = 0; i < n; i++)
    {
        printf ("%s %d\t", (b + i)->name, (b + i)->p);  //Printing values in array of structures
    }

    return 0;
}   
于 2018-05-03T13:51:53.063 回答
0

如果要动态增长数组,则应使用 malloc() 动态分配一些固定数量的内存,然后在用完时使用 realloc()。一种常见的技术是使用指数增长函数,这样您分配一些小的固定数量,然后通过复制分配的数量使数组增长。

一些示例代码是:

size = 64; i = 0;
x = malloc(sizeof(words)*size); /* enough space for 64 words */
while (read_words()) {
    if (++i > size) {
        size *= 2;
        x = realloc(sizeof(words) * size);
    }
}
/* done with x */
free(x);
于 2008-11-04T05:05:23.587 回答
0

这是我在 C++ 中的做法

size_t size = 500;
char* dynamicAllocatedString = new char[ size ];

对任何结构或 c++ 类使用相同的主体。

于 2011-07-13T21:58:19.383 回答