Upgrading my code to include pointers

Hi all,

For my university assignment I need to include pointers in my work (I'm making a battleships game). I currently have the following multi-dimensional array;

1
2
3
4
5
6
7
8
int t,i, nums[5][5]; 
 
  for(t=0; t < 5; ++t) { 
    for(i=0; i < 5; ++i) { 
      nums[t][i] = (t*5)+i+1; 
      cout << nums[t][i] << ' '; 
    } 
    cout << '\n'; 


which produces 5 rows and 5 columns with numbers 1-25.


I currently have the following system to assign the various ships to locations;
1
2
3
4
5
6
7
8
cout << "Please enter a value between 1 and 25 to place the Aircraft Carrier" << endl;  
    cin >> placeAirCarr;

if (placeAirCarr > 25)
   {
    cout << "Please enter a value less than 25" << endl;
    cin >> placeAirCarr;
   }

which is obviously very basic.

My question is, how can I use pointers instead to do this? I've not been able to find anything either clear or relevant about pointers in multi-dimensional arrays.

Thank you in advance :)
this is just example (signal) on how to make one pointer:
1
2
int* nums [5] = new int [5] [5];
delete [] nums;


in similar way u should create 6 pointers using for loop.
Hi,
1
2
3
4
5
6
7
8
9
10
int i,j;
    i=j=5;
    int **nums=new int* [i];
    for (int k=0;k<j;k++)
        nums[k]=new int [j];
    //So you can use nums[a] [b] form to access elements
    //But this is very slow 
    for (int k = 0; k<i;k++)
        delete [] nums[i];
    delete nums;

Another variant is to remember that your nums[5] [5] is the same as nums [5*5]
1
2
3
    int * nums=new int [i*j];
    delete nums;
//Use nums [i*(x-1)+(y-1)] to get access to nums [x] [y] 
Last edited on
So Fandox, would I use something like;
 
*nums [1][1]

to point to the location at co-ordinate 1,1? And with some sort of cin look like;
 
cin >> *nums [1][1]
?

many thanks by the way :)
If you want to use first variant -> use:
nums [1][1] or *(*(nums+1)+1)
it means
cin>>nums [1][1];
In my opinion the second variant is much better
Last edited on
Topic archived. No new replies allowed.