two dimensional array w/ pointers

Hi, Everyone,

I'm new to C++ and I've been trying to figure this out for the past two days.

I have to make a function that allows the user to print out a row of the array, using pointer arithmetic to print the data.(starting at column 0 and finishing at 9)

Here is what I have:



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <cstdlib>
#include <iostream>
using namespace std;
   
int array[10][10];
int *arrayPtr;


int main ()
{
 
 
 int count = 0;
 int arr1;   
   
  for ( int n=0; n<10; n++)
  {
      for(int j=0; j<10; j++)
      {
         array[n][j]= n+count;
         array[n][j] = count++; 
         cout<<array[n][j]<<"\t";  
           
  }
   
}
  //This is what I'm trying to do, but into a function
  arrayPtr = &array[0][0]; 
  cout<<*(arrayPtr)<<endl; 
  cout<<*(arrayPtr + 1)<<endl;
  cout<<*(arrayPtr + 2)<<endl;
  cout<<*(arrayPtr + 3)<<endl;
  cout<<*(arrayPtr + 4)<<endl;
  cout<<*(arrayPtr + 5)<<endl;
  cout<<*(arrayPtr + 6)<<endl;
  cout<<*(arrayPtr + 7)<<endl;
  cout<<*(arrayPtr + 8)<<endl;
  cout<<*(arrayPtr + 9)<<endl;

  system("PAUSE");
  return 0;


}


Thanks for any help or guidance on this. I really appreciate all responses.
Is it specifically mentioned that you need to use a pointer ?
because you can use the array itself as the pointer (const pointer and do pointer arithmetic). Not sure if you already know this, but just letting you know.

eg:

int a[10][10];
a[1][2]=5;
cout<<*(*(a+1)+2); ==> will print 5
Yes, you have to use a pointer.

is the + 1 moving the row over by 1 and +2 moving column over by 2?

*(*(a+1)+2) is the same as a[1][2]

ok let me try to break this down: (assuming you don't know this. If you do, thats great! )

note: <=> means equivalent.

arrayPtr = &array[0][0]; <=> &*(*array+0)+0) <=> (*array) <=> array[0]

*(arrayPtr) <=> *(*array) <=> *(*array+0)+0)
*(arrayPtr +1) <=> *((*array) +1) <=> *(*array+0)+1) <=> array[0][1]

So the series of statements that you have provided prints all the elements in the 0th row.
if you want to write a general function for this you would need to pass the pointer to the function:

void funcToPrintRows( int* tempa ) // Formal argument
{
here use tempa
}
Last edited on
Topic archived. No new replies allowed.