Answer the question
In order to leave comments, you need to log in
How to correctly pass a pointer or a reference to a dynamic array to a function?
Good afternoon! I'm trying to figure out which is better and how to transfer?
For example, I have the following code: - in it I pass a one-dimensional array by reference?
how to pass it by pointer? I encountered when passing by pointer that I don’t understand where and what needs to be dereferenced, for example, in this piece of code!
the next question is how to pass then a two-dimensional array by reference and by pointer and how to access them?
for (int i = 0; i < N; i++) {
for (int j = N - 1; j > i; j--) {
if (mass[j - 1] > mass[j]) {
T3 temp = mass[j];
mass[j] = mass[j - 1];
mass[j - 1] = temp;
template<typename T3,typename T4>
void Bubble( T4 &mass,T3 N){
for ( int i =0;i<N;i++){
cout<<mass[i]<<"\n";
}
for (int i = 0; i < N; i++) {
for (int j = N - 1; j > i; j--) {
if (mass[j - 1] > mass[j]) {
T3 temp = mass[j];
mass[j] = mass[j - 1];
mass[j - 1] = temp;
}
}
}
}
int main(){
int n;
int m;
cout<<"n= ";
cin>>n;
cout<<endl;;
int *mass = new int [n];
for(int i=0;i<n;i++){
cout<<"m = ";
cin>>m;
cout<<endl;
mass[i]=m;
}
cout<<"&mass = "<<&mass<<endl;
Bubble(mass,n);
cout<<"PRINT"<<endl;
for ( int i =0;i<n;i++){
cout<<mass[i]<<"\n";
}
return 0;
}
Answer the question
In order to leave comments, you need to log in
Why complicate? A dynamic array, like yours, is a pointer to an array of pointers, so pass it on. And best of all, of course, vector.
#include <iostream>
#include <vector>
const size_t SIZE = 10;
// const нужен для защиты данных от модификации
template <typename T>
void print1DArray(const T* array, const size_t size)
{
for (size_t i = 0; i < size; ++i) {
std::cout << array[i] << " ";
// благодаря const следующая строка не компилируется
// array[i] = 55;
}
std::cout << std::endl;
std::cout << std::endl;
}
template <typename T>
void print2DArray(const T* const* array, const size_t rows, const size_t columns)
{
for (size_t y = 0; y < rows; ++y) {
for (size_t x = 0; x < columns; ++x) {
std::cout << array[y][x] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
std::cout << std::endl;
}
template <typename T>
void printVector(const std::vector<T>& vector)
{
for (const auto& item : vector) {
std::cout << item << " ";
}
std::cout << std::endl;
std::cout << std::endl;
}
int main()
{
int* array1D = new int[SIZE];
array1D[0] = 99;
array1D[1] = 55;
print1DArray(array1D, SIZE);
delete[] array1D;
int** array2D = new int*[SIZE];
for (size_t i = 0; i < SIZE; ++i) {
array2D[i] = new int[SIZE * 2];
for (size_t j = 0; j < SIZE * 2; ++j) {
array2D[i][j] = i + j;
}
}
print2DArray(array2D, SIZE, SIZE * 2);
for (size_t i = 0; i < SIZE; ++i) {
delete[] array2D[i];
}
delete[] array2D;
std::vector<int> vector(SIZE, 14);
printVector(vector);
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question