如何创建结构的动态大小的数组? [英] How can I create a dynamically sized array of structs?

查看:107
本文介绍了如何创建结构的动态大小的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何创建结构,但与一predefined大小的数组。但是有一种方法创建结构的动态数组,这样的阵列可以得到更大的?

I know how to create an array of structs but with a predefined size. However is there a way to create a dynamic array of structs such that the array could get bigger?

例如:

    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.
    }

这可能吗?

我研究这个:字*阵列=(字*)malloc的(的sizeof(字)* 100);

我不认为我解释清楚我自己,我的道歉。

I don't think I explained myself clearly, my apologies.

我想摆脱100和存储数据,因为它的用武之地。因此,如果数据的76场进来,我想存储76,而不是100.我假设我不知道有多少数据进入我的程序。在结构我在上面我定义可以创建的第一个指数为:

I want to get rid of the 100 and store the data as it comes in. Thus if 76 fields of data comes in, I want to store 76 and not 100. I'm assuming that I don't know how much data is coming into my program. In the struct I defined above I could create the first "index" as:

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

不过,我想动态添加元素后的数组。我希望我所描述的问题方面不够清楚。主要的挑战是动态地添加的第二场,至少是暂时的挑战。

However I want to dynamically add elements to the array after. I hope I described the problem area clearly enough. The major challenge is to dynamically add a second field, at least that is the challenge for the moment.

我已经取得了一点进步但是:

I've made a little progress however:

    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我添加以下内容:

I did some error checking and this is what I found. If after I free up memory for x I add the following:

    x=NULL;

然后如果我尝试打印×1得到一个错误,这就是我想要的。那么,这是免费的功能无法正常工作,至少在我的编译器?我使用DEVC ??

then if I try to print x I get an error which is what I want. So is it that the free function is not working, at least on my compiler? I'm using DevC??

谢谢,我现在明白了,因为:

Thanks, I understand now due to:

名字是指向字符数组是不是由的malloc分配的,只有被分配的指针,你叫自由后,它不会抹去的记忆,它只是将其标记为可用堆要在以后写的。 - 马特·史密斯

FirstName is a pointer to an array of char which is not being allocated by the malloc, only the pointer is being allocated and after you call free, it doesn't erase the memory, it just marks it as available on the heap to be over written later. – MattSmith

P.S。很抱歉的很长的网页,我想我现在已经习惯了这个论坛。

P.S. Sorry for the long page, I guess I'm now getting used to this forum.

我在一个问题。我不知道下一步怎么办。请帮助别人。我试图模块化,把我的结构的数组的创作功能,但它不工作,我尝试了一切,只是似乎没有任何工作。我想很简单的东西,我不知道还能做什么。它像以前一样沿着相同的路线的,只是一个功能,loaddata正在加载数据和方法外,我需要做一些印刷。我怎样才能使它发挥作用?我的code是如下:

I'm in a problem. I have no idea what to do next. Please help someone. I'm trying to modularize and put the creation of my array of structs in a function but it is not working and I've tried everything, just nothing seems to work. I'm trying something very simple and I don't know what else to do. It's along the same lines as before, just another function, loaddata that is loading the data and outside the method I need to do some printing. How can I make it work?. My code is as follows:

    # 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;
    }//

这个简单的测试code崩溃,我不知道为什么。哪里有错误吗?

This simple test code is crashing and I have no idea why. Where is the bug?

推荐答案

您已经标记这是C ++,以及为C。

You've tagged this as C++ as well as C.

如果您正在使用C ++的东西容易得多。标准模板库有一个模板称为矢量,它允许你动态地建立对象的列表。

If you're using C++ things are a lot easier. The standard template library has a template called vector which allows you to dynamically build up a list of objects.

#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的和自由是帮助你的工具。您可能要考虑使用链表数据结构来代替。这些通常很容易增长,但不一样轻松方便的随机访问。

If you're using C things are a lot harder, yes malloc, realloc and free are the tools to help you. You might want to consider using a linked list data structure instead. These are generally easier to grow but don't facilitate random access as easily.

#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的不希望使用链表评论

Yikes, sorry for the worlds longest answer. So WRT to the "don't want to use a linked list comment":

#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;
}

这篇关于如何创建结构的动态大小的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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