Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ 動的配列を関数の引数として渡す | 関数引数の仕様
C++関数

book動的配列を関数の引数として渡す

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

1次元配列の渡し方

1次元の動的配列は、配列へのポインタと配列サイズを別の引数として渡すことで関数に渡すことが可能です。配列は関数に渡す際にポインタへと変換されるため、配列の先頭要素へのポインタを渡すことができます。以下はその方法です:

main.cpp

main.cpp

copy
12345678910111213141516171819202122232425262728
#include <iostream> // Function that takes a dynamic array and its size as parameters void process(int* arr, const int size) { // Access elements of the array using the pointer and the size for (int i = 0; i < size; ++i) std::cout << arr[i] << " "; std::cout << std::endl; } int main() { // Dynamic array allocation int size = 5; int* dynamic_array = new int[size]; // Initializing the dynamic array for (int i = 0; i < size; ++i) dynamic_array[i] = i * 2; // Passing the dynamic array to the function process(dynamic_array, size); // Deallocate the dynamic array to prevent memory leaks delete[] dynamic_array; }

processArray() 関数は、動的整数配列(int*)とそのサイズを引数として受け取ります。 main() では、サイズ5の動的配列を作成・初期化し、配列名とサイズを使って関数に渡します。

2次元配列の受け渡し

動的な2次元配列(各ポインタが要素の配列を指すポインタの配列)を扱う場合、ポインタへのポインタとして配列とその次元数を関数に渡すことが可能。

main.cpp

main.cpp

copy
1234567891011121314151617181920212223242526272829303132333435
#include <iostream> // Function that takes a dynamic 2D array and its size as parameters void process(int** arr, int rows, int cols) { for (int i = 0; i < rows; i++) for (int j = 0; j < cols; j++) arr[i][j] = i * cols + j; // Fill array with values for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) std::cout << arr[i][j] << " "; std::cout << std::endl; } } int main() { int rows = 3; int cols = 4; // Dynamic 2D array allocation int** dynamicArray = new int*[rows]; for (int i = 0; i < rows; i++) dynamicArray[i] = new int[cols]; // Pass the 2D array to the function process(dynamicArray, rows, cols); // Deallocate the dynamic 2D array for (int i = 0; i < rows; i++) delete[] dynamicArray[i]; delete[] dynamicArray; }

process() 関数は動的に確保された2次元配列(int**)とその次元数をパラメータとして受け取り、配列に値を格納する。 配列は名前を使って関数に渡される。

question mark

動的な1次元整数配列を受け取る関数を正しく宣言する方法はどれか?

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

すべて明確でしたか?

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

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

セクション 2.  5

AIに質問する

expand

AIに質問する

ChatGPT

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

セクション 2.  5
some-alt