+ 1
how to merge two arrays in C???
14 Answers
+ 4
Mirielle[ INACTIVE ] that's simply not true, you can easily do it using memcpy.
as rodwynnejones has stated, you need an array that have enough space for the total amount of the 2 arrays.
here is how you can do it in C.
#include <stdio.h>
#include <string.h>
int main(){
int a[10] = {1, 2, 3};
int b[10] = {4, 5, 6};
int aLen = 3, bLen = 3;
memcpy(a + aLen, b, sizeof(int) * bLen);
printf("a = ");
for (int i=0; i<(aLen+bLen); i++){
printf("%d ", a[ i ]);
}
return 0;
}
>>>
a = 1 2 3 4 5 6
+ 3
here is a way (just for playing around ;)
#include <stdio.h>
#include <alloca.h>
#include <stddef.h>
static int* mergeStack(int* a, size_t aS, int* b, size_t bS)
{
// error check
// ...
int* ret = alloca((aS + bS) * sizeof(int));
if (ret == NULL)
{
return ret;
}
for (int i = 0; i < aS; i++)
{
ret[i] = a[i];
}
for (int i = 0; i < bS; i++)
{
ret[i+aS] = b[i];
}
return ret;
}
int main()
{
int a[] = { 1, 2, 3 };
int b[] = { 4, 5, 6 };
int* x = mergeStack(a, 3, b, 3);
for (int i = 0; i < 6; i++)
{
printf("%d\n", x[i]);
}
return 0;
}
// out:
1
2
3
4
5
6
+ 2
What do you mean by merging?
+ 1
You need to make the third array large enough to hold them both, use a for loop for each array and assign to the third...but...initialise/declare the increment variable outside the loops.
I should of asked really...how do you want them merged?
example:-
int arr1[] = {1,2,3,4,5};
int arr2[] = {6,7,8,9,10};
int size = sizeof arr1/ sizeof arr1[0];
int arr3[size * 2];
int i;
for(i = 0; i < size; i++)
arr3[i] = arr1[i];
for(int j = 0 ; j < size; i++, j++)
arr3[i] = arr2[j];
for(i = 0 ; i < size * 2; i++)
printf("%d ", arr3[i]);
+ 1
...or
int arr1[] = {1,2,3,4,5};
int arr2[] = {6,7,8,9,10};
int size = sizeof arr1/ sizeof arr1[0];
int arr3[size * 2];
for(int i = 0; i < size; i++){
arr3[i] = arr1[i];
arr3[i + size] = arr2[i];
}
for(int i = 0 ; i < size * 2; i++)
printf("%d ", arr3[i]);
+ 1
thanks)🤝
+ 1
While Flash's answer is nice, the use of `alloca` should not be used when dealing with enormous amounts of data as it allocates memory to the stack.
Also note that `alloca` is not part of any standard. It is not part of C nor is it part of POSIX.
More info on `alloca` can be found here:
https://www.man7.org/linux/man-pages/man3/alloca.3.html
0
i know that it possible
0
kind if it is array1(123456) and the second array2(789) and when combine.it will be array(123456789)
0
thank you very much
0
👍🏻
0
Rodwynnejones,what do you mean
can you explain?this(int size=sizeof arr1/size of arr1[0] ??because i wrote in code(int r=n/arr1[0]) and it doesnt work correctly
0
sizeof is an operator that returns size of an object/type in bytes Aleks kryzhanivskyi
0
やばいまな板 as I said, it was for fun