动态调整字符串数组 [英] dynamically resizing an array of strings

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

问题描述

`我需要,其中该阵列的长度不是在编译时已知字符串数组。我所做的是:

`I need an array of strings in which the length of the array is not known at compile time. what I've done is:

char **words;
words = malloc(capacity*sizeof(char *));
char nextword[MAX_LEN + 1];

while (true) {
    if (num_entries == capacity) {
        capacity += 5;
        realloc(words, (sizeof(char *) * capacity));
    }
    printf("\nEnter a word: ");
    fgets (nextword, MAX_LEN, stdin);
    remove_newline(nextword);
    if (strlen(nextword) == 0) break;
    words[num_entries] = malloc(strlen(nextword + 1));
    if (words[num_entries] == NULL) {
        printf("\nout of space\n");
        break;
    }
    strcpy(words[num_entries], nextword);
    num_entries++;

此似乎工作一次扩大的大小,所不同的是膨胀后的第一元件已成为空出于某种原因。第二次realloc的执行,我得到一个错误:无效的下一个大小。
在此先感谢

this seems to work to expand the size once, except that the first element after the expansion has become NULL for some reason. The second time realloc is executed I get an error: "invalid next size". thanks in advance

推荐答案

您code是几乎没有,只需要进行一些修改。需要记住的重要事情是,的realloc 不修改传递给它的价值,它不需要指针返回到您传递相同的内存块给它。 下面是使用realloc的的工作示例。这是相当简单的,所以你应该能够通过简单地下面的例子来解决你的code。

Your code is almost there, just need a few modifications. An important thing to remember is that realloc does not modify the value that you pass to it, and it is not required to return the pointer to the same chunk of memory that you passed to it. Here is a working example of using realloc. It is rather straightforward, so you should be able to fix your code by simply following the example.

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

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