You are returning a pointer to a local variable.
k
is created on the stack. When cal()
exits the stack is unwound and that memory is free'd. Referencing that memory afterwards leads to undefined behaviour (as explained beautifully here: https://stackoverflow.com/a/6445794/78845).
Your C++ compiler should warn you about this and you should heed these warnings.
For what it's worth, here is how I'd implement this in C++:
#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
int main()
{
int a[] = {5, 6, 7, 8, 9};
int b[] = {0, 3, 5, 2, 1};
int c[5];
std::transform (a, a + 5, b, c, std::minus<int>());
std::copy(c, c + 5, std::ostream_iterator<int>(std::cout, ", "));
}
See it run!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…