C语言 在 C 中调整数组大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12917727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Resizing an array in C
提问by Sam
Say I assigned an array like so:
假设我像这样分配了一个数组:
char* array[]={"This"};
And then later I wanted to assign array[ ] a new value so that it stores "This" and "That," is there a way that I could change the size of array so that it could hold a new number of values?
后来我想为 array[] 分配一个新值,以便它存储“这个”和“那个”,有没有办法可以改变数组的大小,以便它可以保存新的值?
回答by hmjd
No, you can't change the size of an array. You could use a dynamically allocated list of char*instead and realloc()as required:
不,您不能更改数组的大小。你可以使用动态分配的列表char*,而不是和realloc()要求:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main()
{
char** array = malloc(1 * sizeof(*array));
if (array)
{
array[0] = "This";
printf("%s\n------\n", array[0]);
char** tmp = realloc(array, 2 * sizeof(*array));
if (tmp)
{
array = tmp;
array[1] = "That";
printf("%s\n", array[0]);
printf("%s\n", array[1]);
}
free(array);
}
return 0;
}
See online demo: https://ideone.com/ng00k.
查看在线演示:https: //ideone.com/ng00k。
回答by Ben
There is no way to resize an array. You can simply create a new array of size 2, then copy all the data from the previous one to the new one. reallocdoes it for you with dynamic memory. The better way is to use data structures such as LinkedListsor Vectorswhich you can find more about online.
没有办法调整数组的大小。您可以简单地创建一个大小为 2 的新数组,然后将前一个数组中的所有数据复制到新数组中。 realloc用动态内存为你做。更好的方法是使用诸如LinkedLists或 之类的数据结构Vectors,您可以在网上找到更多相关信息。
回答by John Bode
You cannot resize array objects.
您不能调整数组对象的大小。
You would have to dynamically allocate the memory for arrayand extend it using realloc. Example:
您必须动态分配内存array并使用realloc. 例子:
size_t current_size = 0;
char **array = malloc((current_size + 1) * sizeof *array);
if (array)
{
array[current_size++] = "This";
}
...
/**
* If realloc cannot extend the buffer, it will return NULL and leave
* the original buffer intact; however, if we assign NULL back to array,
* we lose our handle to the original buffer, causing a memory leak, so
* we assign the result to a temporary variable.
*/
char **tmp = realloc(array, (current_size + 1) * sizeof *array)
if (tmp)
{
array = tmp;
array[current_size++] = "That";
}
else
{
// realloc failed to extend the buffer; original buffer
// is left intact.
}
Caveats:
注意事项:
reallocis a relatively expensive call, so you (generally) don't want to extend your buffer one element at a time like I did here. A more common strategy is to pick an initial starting size that covers most cases, and if you need to extend the buffer, double its size.
realloc是一个相对昂贵的调用,因此您(通常)不想像我在这里所做的那样一次扩展一个元素的缓冲区。更常见的策略是选择涵盖大多数情况的初始起始大小,如果需要扩展缓冲区,请将其大小加倍。
You could abstract the resize operation into a separate function, like so:
您可以将调整大小操作抽象为一个单独的函数,如下所示:
int addItem(char ***arr, char *newElement, size_t *count, size_t *bufSize)
{
if (*count == *bufSize)
{
// we've run out of room; extend the buffer
char **tmp = realloc(**arr, 2 * *bufSize * sizeof **arr);
if (tmp)
{
*arr = tmp;
*bufSize *= 2;
}
else
{
// could not extend the buffer; return failure code
return 0;
}
}
(*arr)[(*count)++] = newElement;
}
and call it as
并将其称为
#define N ... // initial array size
char **array = malloc(N * sizeof *array);
size_t bufSize = N;
size_t count = 0;
...
if (addItem(&array, "This", &count, &bufSize))
printf("# elements = %zu, buffer size = %zu\n", count, bufSize);
if (addItem(&array, "That", &count, &bufSize))
printf("# elements = %zu, buffer size = %zu\n", count, bufSize);
This is all untested and off the top of my head; no warranties express or implied. But it should be enough to point you in the right direction.
这一切都未经测试,而且在我的脑海里;不作任何明示或暗示的保证。但这应该足以为您指明正确的方向。
回答by Olaf Dietsche
This is not possible. You can allocate an array of char*, though:
这不可能。不过,您可以分配一个 char* 数组:
char **array = calloc(2, sizeof(char *));
array[0] = "This";
array[1] = "That";

