関数の引数として静的配列を渡す
メニューを表示するにはスワイプしてください
1次元配列を引数として渡す
1次元配列を関数に渡すには、関数シグネチャのパラメータ名の後に**[]**を付ける。
main.cpp
123456789101112131415161718192021#include <iostream> // Function to process a 1-dimensional static array void process(int arr[], const int size) { for (int i = 0; i < size; ++i) std::cout << arr[i] << " "; // Print each element of the array std::cout << std::endl; } int main() { const int SIZE = 5; // Initialize a 1-dimensional static array int oneDimArray[SIZE] = {1, 2, 3, 4, 5}; // Call the function to process the array std::cout << "Original Array: "; process(oneDimArray, SIZE); }
2次元配列を引数として渡す
2次元配列を関数に渡す方法は1次元配列と同様で、パラメータ名の後に[][]を付ける。
ただし、重要な違いがある。C++では、datatype arrayName[][]のように次元を指定せずに関数パラメータを宣言することはできない。
配列の要素にアクセスする際にコンパイラがメモリオフセットを正しく計算できるよう、**列数(または一方の次元)**を必ず指定する必要がある。
main.cpp
1234567891011121314151617181920212223#include <iostream> // Function to print a 2D array with a fixed number of columns void process(int matrix[][3], const int rows) { // Loop through rows for (int i = 0; i < rows; ++i) { for (int j = 0; j < 3; ++j) // Loop through columns std::cout << matrix[i][j] << " "; // Print each element std::cout << std::endl; // Move to the next line } } int main() { const int ROWS = 2; int arr[ROWS][3] = {{1, 2, 3}, {4, 5, 6}}; std::cout << "Original Matrix:" << std::endl; process(arr, ROWS); // Pass array and row count to the function }
すべて明確でしたか?
フィードバックありがとうございます!
セクション 2. 章 4
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 2. 章 4