Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

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.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. 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():

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:

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...