Pointer-to-pointer dynamic two-dimensional array - c++

First timer on this website, so here goes..
I'm a newbie to C++ and I'm currently working through the book "Data structures using C++ 2nd ed, of D.S. Malik".
In the book Malik offers two ways of creating a dynamic two-dimensional array.
In the first method, you declare a variable to be an array of pointers, where each pointer is of type integer. ex.
int *board[4];
..and then use a for-loop to create the 'columns' while using the array of pointers as 'rows'.
The second method, you use a pointer to a pointer.
int **board;
board = new int* [10];
etc.
My question is this: which is the better method? The ** method is easier for me to visualize, but the first method can be used in much the same way. Both ways can be used to make dynamic 2-d arrays.
Edit: Wasn't clear enough with the above post. Here's some code I tried:
int row, col;
cout << "Enter row size:";
cin >> row;
cout << "\ncol:";
cin >> col;
int *p_board[row];
for (int i=0; i < row; i++)
p_board[i] = new int[col];
for (int i=0; i < row; i++)
{
for (int j=0; j < col; j++)
{
p_board[i][j] = j;
cout << p_board[i][j] << " ";
}
cout << endl;
}
cout << endl << endl;
int **p_p_board;
p_p_board = new int* [row];
for (int i=0; i < row; i++)
p_p_board[i] = new int[col];
for (int i=0; i < row; i++)
{
for (int j=0; j < col; j++)
{
p_p_board[i][j] = j;
cout << p_p_board[i][j] << " ";
}
cout << endl;
}

The first method cannot be used to create dynamic 2D arrays because by doing:
int *board[4];
you essentially allocated an array of 4 pointers to int on stack. Therefore, if you now populate each of these 4 pointers with a dynamic array:
for (int i = 0; i < 4; ++i) {
board[i] = new int[10];
}
what you end-up with is a 2D array with static number of rows (in this case 4) and dynamic number of columns (in this case 10). So it is not fully dynamic because when you allocate an array on stack you should specify a constant size, i.e. known at compile-time. Dynamic array is called dynamic because its size is not necessary to be known at compile-time, but can rather be determined by some variable in runtime.
Once again, when you do:
int *board[4];
or:
const int x = 4; // <--- `const` qualifier is absolutely needed in this case!
int *board[x];
you supply a constant known at compile-time (in this case 4 or x) so that compiler can now pre-allocate this memory for your array, and when your program is loaded into the memory it would already have this amount of memory for the board array, that's why it is called static, i.e. because the size is hard-coded and cannot be changed dynamically (in runtime).
On the other hand, when you do:
int **board;
board = new int*[10];
or:
int x = 10; // <--- Notice that it does not have to be `const` anymore!
int **board;
board = new int*[x];
the compiler does not know how much memory board array will require, and therefore it does not pre-allocate anything. But when you start your program, the size of array would be determined by the value of x variable (in runtime) and the corresponding space for board array would be allocated on so-called heap - the area of memory where all programs running on your computer can allocate unknown beforehand (at compile-time) amounts memory for personal usage.
As a result, to truly create dynamic 2D array you have to go with the second method:
int **board;
board = new int*[10]; // dynamic array (size 10) of pointers to int
for (int i = 0; i < 10; ++i) {
board[i] = new int[10];
// each i-th pointer is now pointing to dynamic array (size 10) of actual int values
}
We've just created an square 2D array with 10 by 10 dimensions. To traverse it and populate it with actual values, for example 1, we could use nested loops:
for (int i = 0; i < 10; ++i) { // for each row
for (int j = 0; j < 10; ++j) { // for each column
board[i][j] = 1;
}
}

What you describe for the second method only gives you a 1D array:
int *board = new int[10];
This just allocates an array with 10 elements. Perhaps you meant something like this:
int **board = new int*[4];
for (int i = 0; i < 4; i++) {
board[i] = new int[10];
}
In this case, we allocate 4 int*s and then make each of those point to a dynamically allocated array of 10 ints.
So now we're comparing that with int* board[4];. The major difference is that when you use an array like this, the number of "rows" must be known at compile-time. That's because arrays must have compile-time fixed sizes. You may also have a problem if you want to perhaps return this array of int*s, as the array will be destroyed at the end of its scope.
The method where both the rows and columns are dynamically allocated does require more complicated measures to avoid memory leaks. You must deallocate the memory like so:
for (int i = 0; i < 4; i++) {
delete[] board[i];
}
delete[] board;
I must recommend using a standard container instead. You might like to use a std::array<int, std::array<int, 10> 4> or perhaps a std::vector<std::vector<int>> which you initialise to the appropriate size.

In both cases your inner dimension may be dynamically specified (i.e. taken from a variable), but the difference is in the outer dimension.
This question is basically equivalent to the following:
Is int* x = new int[4]; "better" than int x[4]?
The answer is: "no, unless you need to choose that array dimension dynamically."

This code works well with very few requirements on external libraries and shows a basic use of int **array.
This answer shows that each array is dynamically sized, as well as how to assign a dynamically sized leaf array into the dynamically sized branch array.
This program takes arguments from STDIN in the following format:
2 2
3 1 5 4
5 1 2 8 9 3
0 1
1 3
Code for program below...
#include <iostream>
int main()
{
int **array_of_arrays;
int num_arrays, num_queries;
num_arrays = num_queries = 0;
std::cin >> num_arrays >> num_queries;
//std::cout << num_arrays << " " << num_queries;
//Process the Arrays
array_of_arrays = new int*[num_arrays];
int size_current_array = 0;
for (int i = 0; i < num_arrays; i++)
{
std::cin >> size_current_array;
int *tmp_array = new int[size_current_array];
for (int j = 0; j < size_current_array; j++)
{
int tmp = 0;
std::cin >> tmp;
tmp_array[j] = tmp;
}
array_of_arrays[i] = tmp_array;
}
//Process the Queries
int x, y;
x = y = 0;
for (int q = 0; q < num_queries; q++)
{
std::cin >> x >> y;
//std::cout << "Current x & y: " << x << ", " << y << "\n";
std::cout << array_of_arrays[x][y] << "\n";
}
return 0;
}
It's a very simple implementation of int main and relies solely on std::cin and std::cout. Barebones, but good enough to show how to work with simple multidimensional arrays.

this can be done this way
I have used Operator Overloading
Overloaded Assignment
Overloaded Copy Constructor
/*
* Soumil Nitin SHah
* Github: https://github.com/soumilshah1995
*/
#include <iostream>
using namespace std;
class Matrix{
public:
/*
* Declare the Row and Column
*
*/
int r_size;
int c_size;
int **arr;
public:
/*
* Constructor and Destructor
*/
Matrix(int r_size, int c_size):r_size{r_size},c_size{c_size}
{
arr = new int*[r_size];
// This Creates a 2-D Pointers
for (int i=0 ;i < r_size; i++)
{
arr[i] = new int[c_size];
}
// Initialize all the Vector to 0 initially
for (int row=0; row<r_size; row ++)
{
for (int column=0; column < c_size; column ++)
{
arr[row][column] = 0;
}
}
std::cout << "Constructor -- creating Array Size ::" << r_size << " " << c_size << endl;
}
~Matrix()
{
std::cout << "Destructpr -- Deleting Array Size ::" << r_size <<" " << c_size << endl;
}
Matrix(const Matrix &source):Matrix(source.r_size, source.c_size)
{
for (int row=0; row<source.r_size; row ++)
{
for (int column=0; column < source.c_size; column ++)
{
arr[row][column] = source.arr[row][column];
}
}
cout << "Copy Constructor " << endl;
}
public:
/*
* Operator Overloading
*/
friend std::ostream &operator<<(std::ostream &os, Matrix & rhs)
{
int rowCounter = 0;
int columnCOUNTER = 0;
int globalCounter = 0;
for (int row =0; row < rhs.r_size; row ++)
{
for (int column=0; column < rhs.c_size ; column++)
{
globalCounter = globalCounter + 1;
}
rowCounter = rowCounter + 1;
}
os << "Total There are " << globalCounter << " Elements" << endl;
os << "Array Elements are as follow -------" << endl;
os << "\n";
for (int row =0; row < rhs.r_size; row ++)
{
for (int column=0; column < rhs.c_size ; column++)
{
os << rhs.arr[row][column] << " ";
}
os <<"\n";
}
return os;
}
void operator()(int row, int column , int Data)
{
arr[row][column] = Data;
}
int &operator()(int row, int column)
{
return arr[row][column];
}
Matrix &operator=(Matrix &rhs)
{
cout << "Assingment Operator called " << endl;cout <<"\n";
if(this == &rhs)
{
return *this;
} else
{
delete [] arr;
arr = new int*[r_size];
// This Creates a 2-D Pointers
for (int i=0 ;i < r_size; i++)
{
arr[i] = new int[c_size];
}
// Initialize all the Vector to 0 initially
for (int row=0; row<r_size; row ++)
{
for (int column=0; column < c_size; column ++)
{
arr[row][column] = rhs.arr[row][column];
}
}
return *this;
}
}
};
int main()
{
Matrix m1(3,3); // Initialize Matrix 3x3
cout << m1;cout << "\n";
m1(0,0,1);
m1(0,1,2);
m1(0,2,3);
m1(1,0,4);
m1(1,1,5);
m1(1,2,6);
m1(2,0,7);
m1(2,1,8);
m1(2,2,9);
cout << m1;cout <<"\n"; // print Matrix
cout << "Element at Position (1,2) : " << m1(1,2) << endl;
Matrix m2(3,3);
m2 = m1;
cout << m2;cout <<"\n";
print(m2);
return 0;
}

int row, col;
cout << "Enter row size:";
cin >> row;
cout << "\ncol:";
cin >> col;
int *p_board[row];
for (int i=0; i < row; i++)
p_board[i] = new int[col];
for (int i=0; i < row; i++)
{
for (int j=0; j < col; j++)
{
p_board[i][j] = j;
cout << p_board[i][j] << " ";
}
cout << endl;
}
cout << endl << endl;
// in this method of declaring 2d array using new ..first you have created an array of pointers locally not using new so it will be created on stack not on heap then you have created an array using new on every index of p_board, these all arrays are created on heap but due to locally created p_board will make these array of no use becoz when you will use this method in any function and will try to return the p_board pointer from that function ..at that time p_board will be vanished from stack because it was created on stack ...but 2nd method is preferable to use/
int **p_p_board;
p_p_board = new int* [row];
for (int i=0; i < row; i++)
p_p_board[i] = new int[col];
for (int i=0; i < row; i++)
{
for (int j=0; j < col; j++)
{
p_p_board[i][j] = j;
cout << p_p_board[i][j] << " ";
}
cout << endl;
}
//in this method both array will be created on heap

Related

Exception assembly code error with a matrix to array function conversion call in main function

I'd like to convert a Matrix into an array, which I managed to do inside the main function, but when time to come to put it in a function, it stops working and I get an access violation error which didn't show inside the main scope.
Here is the code, I need help to complete the conversion. I need to cast it from a class function for my project.
#include <iostream>
const int rows = 3, cols = 4; //define constant rows and columns
int* MatrixToArray(static int* matrix[rows][cols]) {
int* array[rows*cols]{};//initialize the array
int* ptrResult=nullptr;//initialize the return variable
//First loop to fill the matrix with dissociated values to print out
for (int i = 0; i < rows-1; i++) {
for (int j = 0; j < cols-1; j++) {
if (matrix) {
*matrix[i][j] = i + j + i * (j + cols); ///exception violation access memory
}
if (matrix) {//debug warning C6011
std::cout << " [" << *matrix[i][j] << "]";
}
}
std::cout << ",\n";
}
//second reversed loop to get the unified array from the previous matrix
for (int u = 0; u < 1; u++) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (array) {//debug warning C6011
array[u] = matrix[i][j];
if (ptrResult) {//debug warning C6011
ptrResult = array[u];
}
}
std::cout << "[" << *array[u] << "] ";
}
}
}
free(array);
return ptrResult;
}
int main()
{
int* matrix[rows][cols];
std::cout << MatrixToArray(matrix);
}
After adapting the types for the matrix and the array, I get this code :
#include <iostream>
const int rows = 3, cols = 4; //define constant rows and columns
int* MatrixToArray(int** matrix) {
int* array[rows*cols]{};//initialize the array
int* ptrResult=nullptr;//initialize the return variable
//allocate memory as requested in the subedit comment field answers
matrix = new int* [rows];
for (int i = 0; i < rows; ++i)
matrix[i] = new int[cols];
//First loop to fill the matrix with dissociated values to print out
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix) {
matrix[i][j] = i + j + i * (j + cols); ///exception violation access memory disappear
}
if (matrix) {//debug warning C6011
std::cout << " [" << matrix[i][j] << "]";
}
}
std::cout << ",\n";
}
//second reversed loop to get the unified array from the previous matrix
if (array) {
for (int u = 0; u < 1; u++) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (array) {//debug warning C6011
array[u] = &matrix[i][j];
if (ptrResult) {//debug warning C6011
ptrResult = array[u];
}
}
//std::cout << "[" << *array[u] << "] ";
}
}
}
free(array);//File: minkernel crts ucrt src appcrt heap debug_heap.cpp Line:904 expression: _CrtlsValidHeapPointer(block)
}
return ptrResult;
}
int main()
{
//memory allocation correction
int** matrix;
matrix = new int* [rows];
for (int i = 0; i < rows; ++i)
matrix[i] = new int[cols];
std::cout << MatrixToArray(matrix);
}
I still get an exception error, but in the assembly code which ends up into the message copied in the comment next to the line quoted.
#include <iostream>
const int rows = 3, cols = 4; //define constant rows and columns
int* MatrixToArray(int** matrix) {
int* array= new int[rows * cols]{};//initialize the array (with new keyword)
int* ptrResult=nullptr;//initialize the return variable
matrix = new int* [rows];
for (int i = 0; i < rows; ++i)
matrix[i] = new int[cols];
std::cout << "[";
//First loop to fill the matrix with dissociated values to print out
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix) {
matrix[i][j] = i + j + i * (j + cols); ///exception violation access memory disappeared
}
if (matrix) {//debug warning C6011
std::cout << " [" << matrix[i][j] << "]";
}
}
if (i != rows - 1) {
std::cout << ",\n";
}
}std::cout << "]";
//second reversed loop to get the unified array from the previous matrix
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (array) {//debug warning C6011
array[0] = matrix[i][j]; //modified with new initialization
if (ptrResult) {//debug warning C6011
*ptrResult = array[0];//modified with new initilization
}
}
}
}
delete[] array;
return ptrResult;
}
int main()
{
int** TheMatrix;
TheMatrix = new int* [rows];
for (int i = 0; i < rows; ++i)
TheMatrix[i] = new int[cols];
std::cout << MatrixToArray(TheMatrix);
for (int i = 0; i < rows; ++i) {
delete[] TheMatrix[i];
}
delete[] TheMatrix;
}
Finally, I tweaked the pointers, and I got rid of the exception in the assembly mode, But I get a serie of zeros popping out in the end...
I'd like to convert a Matrix into an array
Given what you have stated in your question, there is no need to turn a two-dimensional array into a one-dimensional array, if the two-dimensional array is either:
A "traditional" C++ array (i.e. int matrix[10][10];) or
A two-dimensional array built from a T** in a contiguous manner.
Both the items above have the same property, and that is the data is in contiguous memory, no different than a single dimension array. Thus a 2-dimensional array is already a 1 dimensional array.
The only difference between item 1 and item 2 above in terms of contiguousness is that item 1 is "pre-built", while item 2 requires you to build the two-dimensional array.
For item 2). the answer here shows a complete class that builds the matrix from any T** in a contiguous manner. The way you're building the 2-dimensional array does not create the data in contiguous memory, since each row is allocated separately.
Once you have the matrix, the way you use it in a one-dimensional fashion is to pass the address of the items to whatever function or entity requires a pointer to a one-dimensional array.
Here is an example (for the int**, we will use the code in the other linked answer).
#include <iostream>
#include <exception>
#include <numeric>
template <typename T>
T** create2DArray(unsigned nrows, unsigned ncols, const T& val = T())
{
if (nrows == 0)
throw std::invalid_argument("number of rows is 0");
if (ncols == 0)
throw std::invalid_argument("number of columns is 0");
T** ptr = nullptr;
T* pool = nullptr;
try
{
ptr = new T*[nrows]; // allocate pointers (can throw here)
pool = new T[nrows*ncols]{val}; // allocate pool (can throw here)
// now point the row pointers to the appropriate positions in
// the memory pool
for (unsigned i = 0; i < nrows; ++i, pool += ncols )
ptr[i] = pool;
// Done.
return ptr;
}
catch (std::bad_alloc& ex)
{
delete [] ptr; // either this is nullptr or it was allocated
throw ex; // memory allocation error
}
}
template <typename T>
void delete2DArray(T** arr)
{
delete [] arr[0]; // remove the pool
delete [] arr; // remove the pointers
}
// The MatrixToArray function takes a pointer to a buffer and prints the info
void MatrixToArray(int data[], int numItems)
{
for (int i = 0; i < numItems; ++i)
std::cout << data[i] << " ";
std::cout << "\n";
}
int main()
{
int test1[] = {1,2,3,4,5,6,7,8,9,10}; // a 1-dimensioanl array
int test2[2][5] = {{1,2,3,4,5},{6,7,8,9,10}}; // a 2-dimensional array
int **test3 = create2DArray<int>(2,5); // a dynamically created 2-d array
// quickly fill the above with the same data as the other arrays
std::iota(&test3[0][0], &test3[1][5], 1);
// Now test each one to prove that the same MatrixToArray function works for
// 1-dimensional and 2-dimensional arrays.
std::cout << "Output 1:\n";
MatrixToArray(test1, 10);
std::cout << "\nOutput 2:\n";
MatrixToArray(&test2[0][0], 10);
std::cout << "\nOutput 3:\n";
MatrixToArray(&test3[0][0], 10);
delete2DArray(test3);
}
Output:
Output 1:
1 2 3 4 5 6 7 8 9 10
Output 2:
1 2 3 4 5 6 7 8 9 10
Output 3:
1 2 3 4 5 6 7 8 9 10
The same output is produced from the MatrixToArray function, regardless if the array is one-dimensional, or if the array is 2-dimensional traditional, or 2-dimensional array built dynamically.

C++, Convert 1D Array into 2D Array

I need to convert code that is currently using two functions to create a character 2D Array into one function that creates a character 2D Array.
The contents of the Array is the alphabet from 'A' to 'Y' (omitting 'Z', as I need a matrix of 5*5 size). Notes: I cannot use vectors or pointers.
The below code works, but it needs to be converted into one function, which I am having considerable trouble doing. I have been researching but I cannot find a clear enough solution, and I am a beginner in C++.
// Fills 4-Square Matrix 1 with Alphabet (1D Array)
void fill4Square1(char* FourSquare_1_Matrix)
{
int n;
for (n = 0; n < 25; n++)
FourSquare_1_Matrix[n] = 'A' + n;
}
// Fills 4-Square Matrix 1 with Alphabet (2D Array)
void fill4Square1_1()
{
char FourSquare_1_Matrix[5][5];
fill4Square1((char*)FourSquare_1_Matrix); //Function Call for 1D Array
for (int row = 0; row < 5; row++) //For Loop puts 1D array into 2D Array
{
for (int col = 0; col < 5; col++)
cout << FourSquare_1_Matrix[row][col] << " ";
cout << "\n";
}
}
I wrote the below code, but I cannot get the contents of the 1D Array into the 2D array. The 2D Array is being filled with random char characters. Program OUTPUT
void PlayFairMatrix1()
{
int i = 0;
char Matrix[25] = { {0} };
char PlayFairMatrix[5][5] = { {0} };
int n;
//1D Matrix
for (i = 0; i < 25; i++)
{
Matrix[i] = 'A' + i;
cout << Matrix[i];
}
cout << "\n";
cout << " " << endl;
////2D Matrix
for (int row = 0; row < 5; row++)
{
for (int col = 0; col < 5; col++)
{
PlayFairMatrix[row][col] = Matrix[i];
i++;
}
cout << PlayFairMatrix << " ";
cout << "\n";
}
cout << " " << endl;
}
Can anyone please help point me in the right direction?
The problem lies on this line PlayFairMatrix[row][col] = Matrix[i];
i starts off with the value 25 from previous loop. And you never reset it back to 0.
So, the simplest way to fix it is just add i = 0; before the second loop.
Another way will accessing Matrix using row and col, but I will leave that for you as an exercise.
Also, when you print PlayFairMatrix, you are not accessing it with index so you will print the pointer instead. You should put cout << PlayFairMatrix << " "; into inner loop and add the index, so it becomes cout << PlayFairMatrix[row][col] << " ";
While populating PlayFairMatrix, you forgot to reinitialize variable i = 0. That will fix your code.
But you can do it simply as follows
void PlayFairMatrix1()
{
char PlayFairMatrix[5][5] = { {0} };
int i = 0;
for(int row = 0; row < 5; ++row)
{
for(int col = 0; col < 5: ++col)
{
PlayFairMatrix[row][col]='A'+i;
}
}
}

Access multidimensional array passed to function

I am looking for a way to access a multidimensional Array that is passed via pointer. I followed the question here (Create a pointer to two-dimensional array) to create my array and a pointer to it. I could even pass the pointer to the function, but I can't use the pointer to access the array values. What's the correct way to access the values inside the function.
main.cpp:
MyArrayGenerator theArrGen = MyArrayGenerator();
const int size = 9;
int generatorArray[size][size][10];
theArrGen.generateArray(size, generatorArray[size][size+1]);
The method in my class:
void MyArrayGenerator::generateArray(int size,int* pointerToMultiDimArr)
{
int height = size + 1;
// this ptr points to the array address
int* ptr = pointerToMultiDimArr;
// not working:
ptr[1][1][1] = 123;
}
this throws the compiler error https://msdn.microsoft.com/de-de/library/fhexbxk9.aspx wich means that the pointer is not declared as array.
I guess my method argument needs to change since it wants a pointer and does not know that it will be an array. My question is: How should the method argument look like and how do I access the array in my method after that. Later on I want the user to input the size of the multidimensional array and
const int size = 9;
is just a placeholder
Use pointer notation to access elements! Here is an example to access and use 2d array's pointer this program prints transpose of a matrix
#include<iostream>
int **arr_input(int row, int col)
{
int **arr;
arr = new int*[row];
for (int i = 0; i < row; i++) //array size
{
*(arr + i) = new int[col];
}
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
cin >> *(*(arr + i) + j);
}
} //input array
return arr;
}
void transpose(int**arr, int row, int col)
{
for (size_t i = 0; i < row; i++)
{
for (size_t j = 0; j < col; j++)
{
cout << *(*(arr + j) + i) << " "; //pointer notation//
}
cout << endl;
}
}
void main(){
int row ,col,**ptr1;
cout << "Enter size of Square Matrix: "; cin >> row; col = row;
cout << "\n\tEnter the elements of Matrix\n";
ptr1 = arr_input(row, col); //calling array input function
cout << "\nAdress of pointer is " << ptr1<<endl;
transpose(ptr1, row, col); //calling transpose function
system("pause");
}

c++ Function creates a 2-d array and returns a pointer to the 2-D array

I am new to c++ and am learning to use pointers and arrays. I am having a hard time with a piece of code that is compiling and appears to be doing what it should, except the output of the pointer in the main function appears to be a memory address, so I must be missing something in the way I am calling or returning the pointer. (I hope I got the terminology right)
in my main function, I created a pointer variable and initialized it to null (professor recommended initializing all vars)
int** ptr1=NULL;
Next I set the pointer equal to my function, which creates the array
ptr1 = makeArray1();
Here is the code for my function.
int** makeArray1()
{
const int ROW = 2;
const int COL = 3;
int** array1 = new int* [ROW]; //This creates the first row of cols
for (int i = 0; i < ROW; i++)
{
array1[i] = new int[COL]; //loop to create next col of all rows
}
for (int i = 0; i < ROW; i++)
{
for (int j = 0; j < COL; j++)
{
cout << endl << "Please enter an integer in the first matrix: ";
cin >> array1[i][j];
}
}
cout << endl;
for (int i = 0; i < ROW;i++)
{
for (int j = 0; j < COL; j++)
{
cout << setw(4) << array1[i][j];
}
cout << endl;
}
cout << endl << endl << "In array 2 array2 = " << *array1;
return array1;
}
The array seems to populate with my input fine, but when I print ptr1 in the main function, it returns a memory address and not the number entered into the array.
Any help would be appreciated.
Printing a pointer will print the value of the pointer. Which is a memory address. If you want to see the value at the beginning of the 2d array you need to dereference the pointer.
try to declare: int** array1 = new int* [ROW];
outside your function if you can
ptr1 is a pointer. No wonder you're getting a memory adress, because a pointer is a memory adress. If you want to print the contents of the array, you would have to dereference the pointer.
Like so:
for(int i=0; i < ROW; i++) {
for(int j=0; j < COL; j++) {
cout<<ptr1[i][j];
}
}

C++ pointers prints out the memory address and not numbers

I really can't understand why this prints out the memory address and not the say {1, 2, 3, 4, 5} if you input 5. How can I fix this? Thanks.
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int columnInput;
//int rowInput;
int** column = NULL;
cin >> columnInput;
column = new(int*[columnInput]);
for (int i = 0; i < columnInput; i++) {
column[i] = new(int[i + 1]);
}
cout << " |";
for (int i = 0; i < columnInput; i++){
cout << setw(3) << column[i] << "|";
}
cout << endl;
return 0;
}
Whether you are looking for a 1D or a 2D dynamic array is not very clear from your code. The pointer-to-pointer variable and the commented out rowInput hint towards the latter, however using simple (i.e. not nested) for loops points to the former. In the case you want a 1D dynamic array, Learner's answer is probably what you're looking for. Otherwise, take a close look at this:
#include <iostream>
#include <iomanip>
int main()
{
// I don't really like this, because it can easily lead to name clashes.
// If you really want it, not putting it in global scope is a good idea.
using namespace std;
int ** matrix = 0;
int rows;
int cols;
cin >> rows;
cin >> cols;
// The convention is that the first dimension denotes the number of rows.
// As an exercise, you can try to do the same with columns first.
matrix = new int * [rows]; // reserve pointers for all rows
for (int i = 0; i < rows; i ++) {
matrix[i] = new int[cols]; // reserve space for each row
}
// In order to access a 2D array you typically need nested for loops.
for (int i = 0; i < rows; i ++) {
for (int j = 0; j < cols; j ++) {
matrix[i][j] = 0;
matrix[i][j] += (i % 10) * 10; // <- try commenting this out
matrix[i][j] += j % 10 + 1; // <- same with this here
}
}
cout << endl;
// Same here.
for (int i = 0; i < rows; i ++) {
for (int j = 0; j < cols; j ++) {
cout << setw(3) << matrix[i][j] << "|";
}
cout << endl;
}
// Don't forget to do cleanup!
for (int i = 0; i < rows; i ++) {
delete [] matrix[i];
}
delete [] matrix;
return 0;
}
Online Demo
As others mentioned, since this is C++, using std::vector is a better option here. This nice article over at cplusplus.com explores this and other options.
You're printing a pointer. How could operator<< possibly know how many elements the pointer points to? It can't If you want to print the contents of an array or what a pointer points to then you'll have to write that yourself.
Because column is a pointer to pointer to integer..int** column = NULL printing column directly would give you address instead of integer values.
If you want to allocate dynamic memory according to the user input and want to print it's content use this:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
int columnInput;
int* column = NULL;
cin >> columnInput;
column = new int[columnInput];
for (int i = 0; i < columnInput; i++) {
column[i] = i;
}
cout << " |";
for (int i = 0; i < columnInput; i++){
cout << setw(3) << column[i] << "|";
}
cout << endl;
return 0;
}
If you want to print a pointer's value, you have to put a * before the variable. This says to the compiler "Hey, here comes a pointer, give to me what is pointing at"
So, if ptr is a pointer, for example
*int ptr;
if you want to print ptr's value:
cout << *ptr;
This logic applies to every variable in C/C++.
If you have
int*** listOfListsOfListsOfInts;
And you want to print what's pointing at,
cout << ****listOfListsOfListsOfInts;
Whit a wildcard behind a variable, you get what a pointer is pointing at instead of the memory address that pointer is holding.