Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ 関数から配列を返す | 関数の戻り値の仕様
C++関数

book関数から配列を返す

メニューを表示するにはスワイプしてください

重要な制限事項:関数から返せるのは動的配列のみです。この制限は関数のローカルスコープに起因します。関数内で作成された静的配列は、その関数内でのみアクセス可能です。

ローカルで作成した配列を返そうとすると、関数のスコープによる制限により問題が発生します(存在しない変数のアドレスを返そうとするため、エラーになります)。

動的配列の返却

ローカル変数とは異なり、関数終了時に解放されることはありません。new[] を使って動的に確保したメモリは、作成された関数のスコープを超えてデータが保持されます。そのため、関数内で作成した変数のアドレスを使ってアクセスできます。

動的配列を返すには、関数シグネチャで以下の型指定子を使用します:

  • 1次元配列の場合は dataType*
  • 2次元配列の場合は dataType**
main.cpp

main.cpp

copy
12345678910111213141516171819
#include <iostream> // Function to create and return a dynamic 1D array int* createArray(const int size) { int* arr = new int[size]; for (int i = 0; i < size; ++i) arr[i] = i + 1; // Example initialization return arr; } int main() { int size = 5; int* myArray = createArray(size); // Don't forget to delete the dynamically allocated memory delete[] myArray; }

関数は、指定されたサイズの整数配列のために動的にメモリを割り当てる。配列の各要素には 1 から配列の size までの値が初期化される。関数は、動的に割り当てられた整数配列の最初の要素へのポインタを返し、これを main() ブロック内で使用できる。

main.cpp

main.cpp

copy
1234567891011121314151617181920212223242526272829303132333435
#include <iostream> // Function to create and return a dynamic 2D array int** createArray(const int rows, const int cols) { int** arr = new int*[rows]; for (int i = 0; i < rows; ++i) { arr[i] = new int[cols]; for (int j = 0; j < cols; ++j) { arr[i][j] = i * cols + j + 1; // Example initialization } } return arr; } int main() { int rows = 3; int cols = 2; int** myArray = createArray(rows, cols); // Use the returned 2D array for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { std::cout << myArray[i][j] << " "; } std::cout << std::endl; } // Don't forget to delete the dynamically allocated memory for (int i = 0; i < rows; ++i) { delete[] myArray[i]; } delete[] myArray; return 0; }

原理は1次元配列を返す場合と同じであるが、唯一の違いは、2次元配列を返すために int** 型指定子を使用してポインタの配列へのポインタを返す必要がある点である。

question mark

関数から配列を返す場合について正しい記述はどれですか?

正しい答えを選んでください

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 3.  2

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 3.  2
some-alt