简体   繁体   English

使用ANSI C的动态数组

[英]Dynamic array using ANSI C

I have a char array 我有一个字符数组

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

How can I add some extra items to it in the end? 最后如何添加一些额外的项目? data[]="66";

I'd like a dynamic array in C. 我想要一个C语言中的动态数组。

Thanks 谢谢

Arrays created using the [] syntax are not dynamic, the length is set at compile-time and cannot change. 使用[]语法创建的数组不是动态的,长度是在编译时设置的,不能更改。

UPDATE : Actually, C99 adds so-called "variable-length arrays", which can get their length at run-time. 更新 :实际上,C99添加了所谓的“可变长度数组”,可以在运行时获取它们的长度。 After they've been initialized, however, they can't shrink or expand so the below still applies. 但是,在初始化之后,它们将无法收缩或扩展,因此以下内容仍然适用。

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. 但是,当您拥有指针时,数组将被简单地表达:数组可以表示为指向第一个元素和长度的指针。

So, you can create a new array by dynamically allocating memory using malloc() : 因此,您可以使用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. 您不能在此处使用{}元素列表,仅在初始化使用[]语法声明的数组时才可用。

To grow the array, you can use the realloc() function to re-allocate the memory and copy the old values over: 要增加数组,可以使用realloc()函数重新分配内存并将旧值复制到以下位置:

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

Note that every time you call malloc() (or realloc() ), it can return NULL if it failed to allocate the requested block. 请注意,每次调用malloc() (或realloc() )时,如果未能分配所请求的块,它都可以返回NULL That's why the if statements are needed. 这就是为什么需要if语句的原因。 I cut the initial size down a bit from your example to reduce the number of assignment-lines needed, to make the example shorter. 我从您的示例中减少了初始大小,以减少所需的分配行数,从而使示例更短。

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. 通过使后者的值成块增加,可以减少内存分配的总数,当然要花一些内存。

vc_vector vc_vector

vc_vector* vector = vc_vector_create(0, sizeof(const char *), NULL);

vc_vector_push_back(vector, "11");
vc_vector_push_back(vector, "22");
vc_vector_push_back(vector, "33");

for (int i = 0; i < vc_vector_count(vector); ++i) {
  printf("%s ", (const char*)vc_vector_at(vector, i));
}

// output: 11 22 33

vc_vector_release(vector);

Here is a macro based solution for a dynamic array in C with a very nice syntax to use. 是C语言中动态数组的基于宏的解决方案,使用的语法非常好。 Works for any data type. 适用于任何数据类型。

#include <stdio.h>
#include <stdlib.h>
#include <wondermacros/array/dynamic_array.h>

int main()
{
  int* elems = NULL; /* Initialize a dynamic array. */
  W_DYNAMIC_ARRAY_PUSH(elems, 1, 2, 3, 4); /* Push some elements. */

  /* Iterate all elements. */
  W_DYNAMIC_ARRAY_FOR_EACH(int, e, elems) {
    printf("%d\n", e);
  }

  W_DYNAMIC_ARRAY_FREE(elems); /* Free the array only this way since there is a hidden header. */
}

The library uses Boost pre-processor library so Boost library needs to be there at build time. 使用Boost预处理程序库,因此Boost库需要在构建时存在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM