In my assignment I am supposed to use a pointer to create a 2-D array dynamically. Initialize each element in the array to the sum of its row and column. Then display each element of the array on the console.

I have the program written and it works except for the part that says initialize each element in the array to the sum of its row and column.

For the life of me I cannot wrap my head around how to do that. Can anyone give me a little help or suggestion as to a best method. I have set it to initialize everything to zero at the moment.

I tried doing this with no success

for (int j=0;j<5;j++) //initalize array elements to sum of row and column
	{
		for (int i=0;i<5;i++)
 			p[i][j]=i+2;

	}
//Scott 
// Homework Chapter 14A



#include "stdafx.h"
#include <iostream>
#include <iomanip>

#define frz system("pause");

using namespace std;


int main()
{
	int **p;

	p=new int* [5];//creates 2 rows
	
	
	for(int row=0;row<5;row++)//creates 2 columns
		p[row]=new int[5];

	
	cout<<"Base address of memory pointer: "<<p<<endl;


	for (int j=0;j<5;j++) //initalize array elements to sum of row and column
	{
		for (int i=0;i<5;i++)
 			p[i][j]=0;

	}

	for (int j=0;j<5;j++)
	{
		for (int i=0;i<5;i++)
			cout<<setw(5)<<p[i][j];
		cout<<endl;

	}



	
	cout<<endl;
	p=NULL;
	delete [5] p; //deallocate dynamic memory
	cout<<"Base address of memory pointer: "<<p<<endl;
	cout<<endl;

	frz;
	return 0;
}

if I say p=i I get the following error.

1>i:\c++\homework chapter 14a\homework chapter 14a\homework chapter 14a.cpp(32) : error C2440: '=' : cannot convert from 'int' to 'int *'
1> Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast


please forgive my ignorance, I have been coding for 14hours so far today. I am beat.

Edited 6 Years Ago by scott6480: n/a

if I say p=i I get the following error.
<snip>

p is the address of the starting point of a row - you can't assign a value to that. You have to give both row and column index, as you did in the code you posted earlier

for (int j=0;j<5;j++) //initalize array elements to sum of row and column
	{
		for (int i=0;i<5;i++)
 			p[i][j]=0;

	}

All you're missing for your task is the value to assign to p[j], namely, i+j.

This article has been dead for over six months. Start a new discussion instead.