如何在 C 中连接两个动态 int 数组?
How can I concat two dynamic int-arrays in C?
我的问题是将两个动态分配的 int 数组连接到其中一个。
我猜从逻辑上讲,它应该可以工作...
我提示函数里面的realloc(...)
是错误的。
我也在函数外试了一下,也没用
void concatArrays(int *numbers1, int length1, int *numbers2, int length2)
{
numbers1 = realloc(numbers1, (length1+length2) * sizeof(int));
int counter = 0;
for(int i = length1; i<(length1+length2); i++)
{
numbers1[i] = numbers2[counter];
counter++;
}
}
现在在 main()
中,我填充了两个数组,至少我想打印出新的、更长的数组 (numbers1)。
int main()
{
int length1 = 5;
int *numbers1 = malloc(length1 * sizeof(int));
// fill array1
. . .
int length2 = 4;
int *numbers2 = malloc(length2 *sizeof(int));
// fill array2
. . .
concatArrays(numbers1, length1, numbers2, length2);
// print out "new" array (numbers1)
int new_len = length1 + length2;
for(int i = 0; i<new_len; i++)
{
printf("%d ", numbers1[i]);
}
free(numbers1);
free(numbers2);
}
提前感谢您的所有建议!
realloc() returns 一个新的指针(通常),除非新的大小只是稍微大一点并且可以适应过度分配的数组。您没有将新指针 'numbers1' 传递回调用函数。
我的问题是将两个动态分配的 int 数组连接到其中一个。 我猜从逻辑上讲,它应该可以工作...
我提示函数里面的realloc(...)
是错误的。
我也在函数外试了一下,也没用
void concatArrays(int *numbers1, int length1, int *numbers2, int length2)
{
numbers1 = realloc(numbers1, (length1+length2) * sizeof(int));
int counter = 0;
for(int i = length1; i<(length1+length2); i++)
{
numbers1[i] = numbers2[counter];
counter++;
}
}
现在在 main()
中,我填充了两个数组,至少我想打印出新的、更长的数组 (numbers1)。
int main()
{
int length1 = 5;
int *numbers1 = malloc(length1 * sizeof(int));
// fill array1
. . .
int length2 = 4;
int *numbers2 = malloc(length2 *sizeof(int));
// fill array2
. . .
concatArrays(numbers1, length1, numbers2, length2);
// print out "new" array (numbers1)
int new_len = length1 + length2;
for(int i = 0; i<new_len; i++)
{
printf("%d ", numbers1[i]);
}
free(numbers1);
free(numbers2);
}
提前感谢您的所有建议!
realloc() returns 一个新的指针(通常),除非新的大小只是稍微大一点并且可以适应过度分配的数组。您没有将新指针 'numbers1' 传递回调用函数。