c - 如何在C中动态地在数组的最后一个位置插入一个元素?

标签 c arrays dynamic-memory-allocation

我是 C 语言的新手,尝试在 C 语言的最后一个位置插入一个数字,这样数组的大小会随着时间的推移而改变。

第一个数组是这样的:

temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};

现在我们如何将 temp!= 0 的值插入到定义长度为 5 的新数组中:tmp

这就是我正在尝试的:

void push(int arr[], int value, int current){
  arr[current] = value;
}

int main(void) { 

  int temp[10] = {1, 2, 0, 0, 5, 6, 0, 8, 0, 0};
  int tmp[5];

  for(int i=0;;i++){
    if(temp[i]) push(tmp, temp[i],sizeof(tmp)/sizeof(tmp[0]));
    // I don't put i < 10 int the loop initialization. Since the tmp's length is just 5

  }
  // I put sizeof(tmp)/sizeof(tmp[0]) there because we want at every time the tmp is inserted a new value,
  // it's length will change (increase by 1). 
  // So next loop round, the new value will be added to the last position
  // But I failed to do so

} 

当前输出:

exited segmentation fault
// I'd be very grateful if someone can also explain for me why this error happens

所需输出:

tmp[5] = {1, 2, 5, 6, 8}

最佳答案

C 没有动态数组。数组具有由其定义确定的固定大小。您可以使用 malloc() 分配像数组一样的对象,但您必须单独跟踪它们分配的大小。追加元素需要重新分配数组,因此其在内存中的地址可能会发生变化。

在您的代码中,tmp 的固定大小为 5 个元素。您可以维护一个索引,指定使用了多少个元素,并在 push 函数中更新该索引:

#include <stdio.h>

int push(int arr[], int value, size_t size, size_t *current) {
    if (*current < size) {
        arr[(*current)++] = value;
        return 0;
    } else {
        /* array is full */
        return -1;
    }
}

int main(void) { 
    int temp[10] = { 1, 2, 0, 0, 5, 6, 0, 8, 0, 0 };
    int tmp[5];
    size_t pos = 0;

    for (size_t i = 0; i < sizeof(temp) / sizeof(temp[0]); i++) {
        if (temp[i])
            push(tmp, temp[i], sizeof(tmp) / sizeof(tmp[0]), &pos);
    }

    printf("tmp:");
    for (size_t i = 0; i < pos; i++) {
        printf(" %d", tmp[i]);
    }
    printf("\n");
    return 0;
}

关于c - 如何在C中动态地在数组的最后一个位置插入一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62083970/

相关文章:

c - 如何找到矿山中最大数量的钻石?

c - 内存映射一个固定位置的数组

JavaScript - 遍历对象以查找特定键值

c - 在结构中保存指向数组的指针

c - 如果堆内存满了会发生什么?

c++ - 使用析构函数是只删除动态分配的数组还是所有数组?

c - 关于C语言中的空字符

c - c中的ilogb()是什么?

arrays - VBA 中的数组下标 - 谁能解释一下?

javascript - JavaScript 中的数字反转