配列を参照する変数は基本的にその最初の要素へのポインターです。したがって、基本的に同じものであるため、配列へのポインターを合法的に返すことができます。これを自分でチェックしてください:
#include <assert.h>
int main() {
int a[] = {1, 2, 3, 4, 5};
int* pArr = a;
int* pFirstElem = &(a[0]);
assert(a == pArr);
assert(a == pFirstElem);
return 0;
}
これは、配列を関数に渡すことは、ポインターを介して(ではなくint in[5]
)ポインターを介して、場合によっては配列の長さとともに実行する必要があることも意味します。
int* test(int* in, int len) {
int* out = in;
return out;
}
とは言うものの、ポインターを(完全に理解せずに)使用することはかなり危険です。たとえば、スタックに割り当てられてスコープ外になった配列を参照すると、未定義の動作が発生します。
#include <iostream>
using namespace std;
int main() {
int* pArr = 0;
{
int a[] = {1, 2, 3, 4, 5};
pArr = a; // or test(a) if you wish
}
// a[] went out of scope here, but pArr holds a pointer to it
// all bets are off, this can output "1", output 1st chapter
// of "Romeo and Juliet", crash the program or destroy the
// universe
cout << pArr[0] << endl; // WRONG!
return 0;
}
したがって、十分な能力がないと感じた場合は、を使用してstd::vector
ください。
[更新された質問への回答]
test
関数を作成する正しい方法は次のいずれかです。
void test(int* a, int* b, int* c, int len) {
for (int i = 0; i < len; ++i) c[i] = a[i] + b[i];
}
...
int main() {
int a[5] = {...}, b[5] = {...}, c[5] = {};
test(a, b, c, 5);
// c now holds the result
}
またはこれ(を使用std::vector
):
#include <vector>
vector<int> test(const vector<int>& a, const vector<int>& b) {
vector<int> result(a.size());
for (int i = 0; i < a.size(); ++i) {
result[i] = a[i] + b[i];
}
return result; // copy will be elided
}