c - 有没有办法将元素添加到列表/数组? [C]

标签 c arrays list

<分区>

我只是想知道我是否可以在 C 中向列表添加/附加元素,我会四处做吗?

例如

int numbers[6] = {5,3,5,1,3,6}

假设我想向数组“numbers”添加另一个数字,我该怎么做?

最佳答案

嗯,原始数组需要被malloc,而不是在堆栈上。然后你可以使用realloc:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int * numbers = malloc(6*sizeof(int));

    for(int ii = 0; ii < 6; ++ii) {
        numbers[ii] = 5;
    }

    numbers = realloc(numbers, 7*sizeof(*numbers));
    if(!numbers) {
        printf("Memory allocation failed, sorry dude!\n");
        exit(1);
    }

    numbers[6] = 7;

    for(int ii = 0; ii< 7; ++ii) {
        printf("%d\n", numbers[ii]);
    }

    free(numbers);
}

关于c - 有没有办法将元素添加到列表/数组? [C],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27736461/

相关文章:

arrays - bash:如何使用一个数组创建另一个数组?

r - 如何查看列表的任何元素是否仅包含 R 中的某个值

list - Delphi 中 Dijkstra 最短路径搜索的优化

c# - 将 List<int> 转换为范围列表

c++ - 在没有 MSVCRT 运行时的情况下在 Visual Studio 2012 中编译 C

c - 带无符号操作数的类型转换 - C

将 Unicode 代码点转换为 UTF-8 和 UTF-32

javascript - 匹配两个数组作为数组的对象

javascript - 如何按月份然后按客户对一系列产品销售进行分组

c - 降低 GTK+ 中的按钮高度