5

假设我分配了一个这样的数组:

char* array[]={"This"};

后来我想给数组[]分配一个新值,以便它存储“这个”和“那个”,有没有办法可以改变数组的大小,以便它可以容纳新的值?

4

4 回答 4

14

不,您不能更改数组的大小。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;
}

见在线演示:https ://ideone.com/ng00k 。

于 2012-10-16T15:06:37.507 回答
4

没有办法调整数组的大小。您可以简单地创建一个大小为 2 的新数组,然后将所有数据从前一个数组复制到新数组。 realloc用动态内存为你做这件事。更好的方法是使用数据结构,例如LinkedListsVectors您可以在网上找到更多信息。

于 2012-10-16T15:07:28.243 回答
2

您不能调整数组对象的大小。

您必须动态分配内存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.
}

注意事项:

realloc是一个相对昂贵的调用,因此您(通常)不想像我在这里所做的那样一次扩展一个元素。一个更常见的策略是选择一个涵盖大多数情况的初始起始大小,如果需要扩展缓冲区,则将其大小加倍。

您可以将调整大小操作抽象为一个单独的函数,如下所示:

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

并将其称为

#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);

这一切都是未经测试的,我无法想象;没有任何明示或暗示的保证。但这应该足以为您指明正确的方向。

于 2012-10-16T15:48:29.067 回答
0

这是不可能的。不过,您可以分配一个 char* 数组:

char **array = calloc(2, sizeof(char *));
array[0] = "This";
array[1] = "That";
于 2012-10-16T15:11:02.967 回答