使用ANSI C动态数组 [英] Dynamic array using ANSI C

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

问题描述

我有一个字符数组

char *data[]= {"11", "22", "33", "44", "55"};

我如何添加一些额外的项目,这到底? 数据[] =66;

我想在C动态数组。

感谢

推荐答案

使用 [] 语法创建数组不是动态的,长度设置在编译时和不能改变。

Arrays created using the [] syntax are not dynamic, the length is set at compile-time and cannot change.

更新:其实,C99增加了所谓的变长数组,它可以在运行时得到他们的长度。他们已经被初始化后,但是,他们不能收缩或扩展所以下面仍然适用。

UPDATE: Actually, C99 adds so-called "variable-length arrays", which can get their length at run-time. After they've been initialized, however, they can't shrink or expand so the below still applies.

然而,阵列是当你有指针pssed平凡前$ P $:一个阵列可重新psented作为指针的第一个元素$ P $和长度

However, an array is trivially expressed when you have pointers: an array can be represented as a pointer to the first element, and a length.

所以,你可以通过使用动态分配内存中创建一个新的数组的malloc()

So, you can create a new array by dynamically allocating memory using malloc():

size_t array_length = 3;
int *array = malloc(array_length * sizeof *array);

if(array != NULL)
{
  array[0] = 11;
  array[1] = 22;
  array[2] = 33;
}

您不能使用此元素的 {} 列表中,这只是可用时初始化数组使用声明的 [] 语法。

You cannot use the {} list of elements here, that's only usable when initializing arrays declared using the [] syntax.

要增长数组,你可以使用的realloc()函数来重新分配存储器中,并且复制旧值:

To grow the array, you can use the realloc() function to re-allocate the memory and copy the old values over:

size_t new_length = array_length + 1;
int *bigger_array = realloc(array, new_length * sizeof *bigger_array);

if(bigger_array != NULL)
{
  bigger_array[new_length - 1] = 44;
  /* We have successfully grown the allocation, remember the new address. */
  array = bigger_array;
  array_length = new_length;
}

请注意,每次你打电话时间的malloc()(或的realloc()),它可以返回 NULL 如果未能分配请求块。这就是为什么需要在如果语句。我将初始大小下来从你的例子有点减少所需的分配线的数量,使例子更短。

Note that every time you call malloc() (or realloc()), it can return NULL if it failed to allocate the requested block. That's why the if statements are needed. I cut the initial size down a bit from your example to reduce the number of assignment-lines needed, to make the example shorter.

为使上面的更有效率,典型的动态数组code使用的两个的长度值:一个是实际的数组(有多少值是数组中现在),一个用于存储(多少值,我们有空间来存储)。通过使后者的值在块生长,内存分配的总数可以降低一点,在当然一些存储器的成本。

To make the above more efficient, typical dynamical array code uses two length values: one for the actual array (how many values are in the array right now) and one for the memory (how many values to we have room to store). By making the latter value grow in chunks, the total number of memory allocations can be cut down a bit, at the cost of some memory of course.

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

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