使用数组动态内存分配 [英] Using Dynamic Memory allocation for arrays

查看:264
本文介绍了使用数组动态内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么使用动态内存分配的数组?

How am I supposed to use dynamic memory allocations for arrays?

例如下面是下面的数组中,我从.txt文件中读取单个单词和单词数组中保存字:

For example here is the following array in which i read individual words from a .txt file and save them word by word in the array:

code:

char words[1000][15];

下面1000定义的字的数量的阵列可以保存和每个字可包含不超过15个字符。

Here 1000 defines the number of words the array can save and each word may comprise of not more than 15 characters.

现在我想要的那个节目应该动态分配的内存为它计算的字数。例如,一个.txt文件可能包含文字大于1000。现在我想程序应该计算单词的数量,并相应地分配内存。

Now I want that that program should dynamically allocate the memory for the number of words it counts. For example, a .txt file may contain words greater that 1000. Now I want that the program should count the number of words and allocate the memory accordingly.

既然我们不能到位[1000]中使用变量,我如何实现我的逻辑完全空白。请帮我在这方面。

Since we cannot use a variable in place of [1000], I am completely blank at how to implement my logic. Please help me in this regard.

推荐答案

您使用指针。

特别是,你用一个指针的地址,并使用标准C库函数调用,你问操作系统扩展堆到允许你存储你所需要的。

Specifically, you use a pointer to an address, and using a standard c library function calls, you ask the operating system to expand the heap to allow you to store what you need to.

现在,它可能会拒绝,你将需要处理。

Now, it might refuse, which you will need to handle.

接下来的问题 - 你怎么问了一个二维数组?好吧,你问一个指针数组,然后展开每个指针。

The next question becomes - how do you ask for a 2D array? Well, you ask for an array of pointers, and then expand each pointer.

作为一个例子,考虑一下:

As an example, consider this:

int i = 0;
char** words;
words = malloc((num_words)*sizeof(char*));

if ( words == NULL )
{
    /* we have a problem */
    printf("Error: out of memory.\n");
    return;
}

for ( i=0; i<num_words; i++ )
{
    words[i] = malloc((word_size+1)*sizeof(char));
    if ( words[i] == NULL )
    {
        /* problem */
        break;
    }
}

if ( i != num_words )
{
    /* it didn't allocate */
}

这让你一个二维数组,其中每个元素字[I] 可以有不同的大小,在运行时确定的,就像单词的数量是

This gets you a two-dimensional array, where each element words[i] can have a different size, determinable at run time, just as the number of words is.

您需要将免费()所有产生的内存通过循环阵列上,当你用它做:

You will need to free() all of the resultant memory by looping over the array when you're done with it:

for ( i = 0; i < num_words; i++ )
{
    free(words[i]);
}

free(words);

如果你不这样做,你会创建一个内存泄漏。

If you don't, you'll create a memory leak.

您也可以使用释放calloc 。所不同的是在调用约定和效果 - 释放calloc 初始化所有的内存 0 ,而的malloc 没有。​​

You could also use calloc. The difference is in calling convention and effect - calloc initialises all the memory to 0 whereas malloc does not.

如果您需要在运行时调整大小,使用的realloc

If you need to resize at runtime, use realloc.

  • Malloc
  • Calloc
  • Realloc
  • Free

此外,重要的是,提防word_size + 1 ,我都习惯了。在C字符串是零结尾,这需要你需要考虑一个额外字符。为了确保我记得这个,我通常设置变量的大小 word_size 到任何字的大小应该是(字符串的长度,如我所料),并明确地离开+1中的malloc零。后来我知道,分配缓冲区可以采取 word_size 字符的字符串。不这样做也很好 - 我只是这样做,因为我喜欢在一个明显的方式来明确占到零

Also, important, watch out for the word_size+1 that I have used. Strings in C are zero-terminated and this takes an extra character which you need to account for. To ensure I remember this, I usually set the size of the variable word_size to whatever the size of the word should be (the length of the string as I expect) and explicitly leave the +1 in the malloc for the zero. Then I know that the allocated buffer can take a string of word_size characters. Not doing this is also fine - I just do it because I like to explicitly account for the zero in an obvious way.

还有一个缺点这种方法 - 我明确看到这是一个错误发运最近。请注意,我写了(word_size + 1)* sizeof的(类型) - 不过可想而知,我写了 word_size *的sizeof(类型)+1​​ 。对于的sizeof(类型)= 1 这些都是同样的事情,但Windows使用 wchar_t的非常频繁 - 在这种情况下, 会为你最后的零,而不是两个预留一个字节 - 它们是一种零终止元素键入,不是单一的零字节。这意味着你将溢出的读写。 &NBSP;

There is also a downside to this approach - I've explicitly seen this as a shipped bug recently. Notice I wrote (word_size+1)*sizeof(type) - imagine however that I had written word_size*sizeof(type)+1. For sizeof(type)=1 these are the same thing but Windows uses wchar_t very frequently - and in this case you'll reserve one byte for your last zero rather than two - and they are zero-terminated elements of type type, not single zero bytes. This means you'll overrun on read and write.  

附录:做任何你喜欢的方式,只是提防那些零终结,如果你打算到缓冲区传递的东西,对他们的依赖

Addendum: do it whichever way you like, just watch out for those zero terminators if you're going to pass the buffer to something that relies on them.

这篇关于使用数组动态内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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