我是 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/