Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Leer Statische Array Doorgeven als Argument van de Functie | Specificatie van Functieargumenten
C++-Functies

Statische Array Doorgeven als Argument van de Functie

Veeg om het menu te tonen

Een 1-dimensionale array als argument doorgeven

Om een 1-dimensionale array aan een functie door te geven, plaats je [] achter de parameternaam in de functiedeclaratie.

main.cpp

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); }

Een 2-dimensionale array als argument doorgeven

Het doorgeven van een 2D-array aan een functie werkt vergelijkbaar met het doorgeven van een 1D-array — je gebruikt [][] achter de parameternaam.

Er is echter een belangrijk verschil: in C++ kun je een functieparameter niet declareren als datatype arrayName[][] zonder ten minste één dimensie te specificeren. Je moet het aantal kolommen (of één dimensie) definiëren zodat de compiler het geheugenadres van de array-elementen correct kan berekenen.

main.cpp

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 }
question mark

Welke functiedeclaratie accepteert correct een 2D statische array als parameter?

Selecteer het correcte antwoord

Was alles duidelijk?

Hoe kunnen we het verbeteren?

Bedankt voor je feedback!

Sectie 2. Hoofdstuk 4

Vraag AI

expand

Vraag AI

ChatGPT

Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.

Sectie 2. Hoofdstuk 4
some-alt