【发布时间】:2019-05-03 11:10:17
【问题描述】:
我正在练习 C 编程。 一项任务是连接两个动态数组。第二个数组的元素应添加到第一个数组的末尾。给出如下:
void concatArrays(int* numbers1, int length1, int* numbers2, int length2)
{
//code
}
这是我解决任务的代码:
#include <stdio.h>
#include <stdlib.h>
void concatArrays(int* numbers1, int length1, int* numbers2, int length2)
{
numbers1 = (int*)realloc(numbers1, sizeof(int*) * (length1 + length2));
for (int count = 0; count < length2; count++)
{
numbers1[length1 + count] = numbers2[count];
}
}
int main()
{
int* num = (int*)malloc(sizeof(int*) * 6);
num[0] = 1;
num[1] = 2;
num[2] = 3;
num[3] = 4;
num[4] = 5;
num[5] = 6;
int* numbers = (int*)malloc(sizeof(int*) * 4);
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
concatArrays(num, 6, numbers, 4);
for (int count = 0; count < 10; count++)
{
printf("%d - ", num[count]);
}
return 0;
}
不幸的是,它不起作用。我知道如果我使用指向指针的指针,代码确实可以工作:
void concatArrays(int** numbers1, int length1, int** numbers2, int length2) { //code }
然而,这似乎是不允许的任务要求。
您知道如何更改我的代码以满足解决任务的要求吗?
提前谢谢你。
编辑:
我忘了:
输出: 1 - 2 - 3 - 4 - 5 - 6 - 2054454589 - 32767 - -1280384664 - 32767 -
【问题讨论】:
-
附带说明,
memcpy是复制数据块的最佳方式。
标签: arrays c concatenation heap-memory