Created
March 2, 2022 20:38
-
-
Save Chamauta/3afe3003ff87c191a1826b8368a305f0 to your computer and use it in GitHub Desktop.
creating dynamic arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
// ================================================== Prototypes ======================================================= // | |
void get(int* (&), int&); // function prototypes | |
void print(int*, int); | |
// ================================================== Source ========================================================== // | |
int main() | |
{ | |
std::cout <<"\n======================= dynamicArrays.cpp ===========================\n"; | |
int* aptr; // aptr is simply an unallocated pointer | |
int n; | |
int numberOfArrays; | |
std::cout << "\nEnter the number of dynamic arrays to create: "; | |
std::cin >> numberOfArrays; | |
std::cout << std::endl; | |
// note: int* aptr == int aptr[] | |
// loop through numberOfArrays to create | |
for (int i = 0; i < numberOfArrays; ++i) | |
{ | |
get(aptr, n); // repopulate arrays with n ints | |
print(aptr, n); | |
delete[] aptr; // deallocate memory | |
aptr = nullptr; // empty aptr | |
} | |
} | |
// ================================================== Definitions ====================================================== // | |
void get(int* &myArrayPtr, int& myArraySize) | |
{ | |
// pass myArrayPtr as reference to int pointer; changes to parameter myArrayPtr (passed as aptr) here, will be seen in main; parenthesis are only for clarity | |
std::cout << "Enter number of elements: "; | |
std::cin >> myArraySize; | |
myArrayPtr = new int[myArraySize]; // heap memory | |
std::cout << "Enter " << myArraySize << " items, one per line:\n"; | |
for (int i = 0; i < myArraySize; i++) | |
{ | |
std::cout << i + 1 << ": "; | |
std::cin >> myArrayPtr[i]; | |
} | |
} | |
void print(int* print_myArrayPtr, int z) // int* myArrayPtr == int myArrayPtr[] | |
{ | |
std::cout << "\nThe elements of the array are: "; | |
for (int i = 0; i < z; i++) | |
{ | |
// note for this loop: myArrayPtr[i] = *(myArrayPtr + i) | |
std::cout << *(print_myArrayPtr + i) << " "; | |
} | |
std::cout << std::endl << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
practice dynamic array creation