Merging two arrays?

I would like to write a code that merges two string arrays and the below is what i have done so far.. and it's not allowed to run
when adding arr1[] and arr2[], i want the arr1 elements to go first and be flowed by arr2 elements

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void mergingArrays(const string arr1[], int n1, const string arr2[], int n2, string output[]) {
	output[1000] = {};
	size = 0;

	for (size_t i = 0; i < n1; i++) {
		int k = 0;
		output[k] = arr1[i];
		k++;
	}
	for (size_t i = n1; i < n2; i++) {
		int k = n1;
		output[k] = arr2[i];
		k++;
	}

	cout << output << endl;

}


what should i correct?? :(
output[1000] = {};
You're trying to access index 1000 of the array, which can lead to undefined behaviour if output doesn't have at least 1001 elements.

1
2
3
4
5
for (size_t i = 0; i < n1; i++) {
    int k = 0;
    output[k] = arr1[i];
    k++;
}

k will be recreated and destroyed every iteration, which means you will keep overwriting the first element of output. This is what you want:
1
2
3
for (int i = 0; i < n1; i++) {
    output[i] = arr1[i];
}

The compiler should warn against a sign/unsigned mismatch because you're comparing an unsigned variable to a signed variable.

I would recommend you use a std::vector instead of arrays, as they allow for an arbitrary amount of elements and will keep your code much easier to read and maintain.
The second for loop starts reading the array from i = n1 instead of i = 0, so arr2[i] might go out of range.

Take out the declaration of k inside the for loop and place it outside the loop.
Topic archived. No new replies allowed.