Skip to content

Instantly share code, notes, and snippets.

@Chamauta
Last active March 2, 2022 19:57
Show Gist options
  • Save Chamauta/83dba49eb9ffda334ae0e41cd7cfdad7 to your computer and use it in GitHub Desktop.
Save Chamauta/83dba49eb9ffda334ae0e41cd7cfdad7 to your computer and use it in GitHub Desktop.
Passing dynamic arrays c++
// elaborated from https://github.com/Headturna/Examples/blob/master/Examples/Example34.cpp
#include<iostream>
// note arrays always pass by reference, so any change within the function modifies the passed array
void test1(int* (arr), int length) // passing a pointer to a function
{
for (int i = 0; i < length; i++)
{
arr[i] = i * 10;
}
}
void test2(int* (&arr), int length) // passing a pointer by reference to a function
{
for (int i = 0; i < length; i++)
{
arr[i] = i * 10;
}
}
void test3(int(arr[]), int length) // passing an array
{
for (int i = 0; i < length; i++)
{
arr[i] = i * 10;
}
}
int main()
{
int arrLength = 10;
int* intArr1 = new int[arrLength]; // create dynamic array; note that arrLength needs not to be const
std::cout << "initializing intArr1\n";
for (int i = 0; i < arrLength; i++) // initialize dynamic array intArr1 to 0
{
intArr1[i] = 0;
/**(intArr1 + i) = 0;*/
std::cout << i << ": " << intArr1[i] << std::endl;
}
std::cout << std::endl;
test1(intArr1, arrLength); // call test1; pass intArr1 a pointer -> test1(int* (arr), int length)
std::cout << "output after calling test1\n";
for (int i = 0; i < arrLength; i++)
{
std::cout << i << ": " << intArr1[i] << std::endl;
}
delete[] intArr1;
std::cout << std::endl;
int* intArr2 = new int[arrLength];
test2(intArr2, arrLength); // call test2; pass intArr2 by as a reference to a pointer -> test2(int* (&arr), int length)
std::cout << "output after calling test2\n";
for (int i = 0; i < arrLength; i++)
{
std::cout << i << ": " << intArr2[i] << std::endl;
}
delete[] intArr2;
std::cout << std::endl;
int* intArr3 = new int[arrLength];
test3(intArr3, arrLength); // call pass intArr3 by pointer as an array -> test3(int (arr[]), int length)
std::cout << "output after calling test3\n";
for (int i = 0; i < arrLength; i++)
{
std::cout << i << ": " << intArr3[i] << std::endl;
}
std::cout << std::endl;
const int myarrLength = 10;
int myStaticArray[myarrLength]{ 0 }; // note that static array requires const myarrLength
std::cout << "output for static array\n";
for (size_t i = 0; i < myarrLength; ++i)
{
myStaticArray[i] = intArr3[i];
std::cout << myStaticArray[i] << "\t";
}
delete[] intArr3;
std::cout << std::endl;
}
@Chamauta
Copy link
Author

Chamauta commented Mar 2, 2022

variations of passing a dynamic array to functions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment