I am writing a program to read in two arrays, the first of length C and the second of length N. Then, it prints the two arrays. However, when my program prints the arrays, it prints strange numbers that never existed in the array. In addition, I have noticed that when I sort the array before printing, the strange numbers disappear when the array is printed.
For example, when C = 10 and N = 10 and both arrays are {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, my program gives this:
First array: 1 2 3 4 5 6 7 8 9 10 4199003 0
First array sorted: 1 2 3 4 5 6 7 8 9 10
Second array: 1 2 3 4 5 6 7 8 9 10 -1159496120 32765 1 2 3 4 5 6 7 8 9 10
Second array sorted: 1 2 3 4 5 6 7 8 9 10
Here is my code:
#include <iostream>
#include <algorithm>
using namespace std;
void println(int arr[]) {
for (int i = 0; i < (&arr)[1] - arr; ++i) {
cout << arr[i] << " ";
}
cout << std::endl;
}
int main () {
int c, n;
cin >> c >> n;
int t[c], a[n];
for (int i = 0; i < c; ++i) {
cin >> t[i];
}
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
cout << "First array: ";
println(t);
sort(t, t+c);
cout << "First array sorted: ";
println(t);
cout << "Second array: ";
println(a);
cout << "Second array sorted: ";
sort(a, a+n);
println(a);
}
I've tried the program using both clang and gnu compilers and they both give me similar results. Why are these numbers appearing and why does sorting eliminate this problem? Any help is appreciated!