getting row/column of dynamic 2d array element

I am currently using the following code to get the current row and column of an element in a 2D int array:

const int num_rows = 5;
const int num_columns = 7;

int a[num_rows][num_columns];

int *p = &a[2][4];

int row = (p - &a[0][0]) / num_columns;
int col = (p - &a[row][0]);

This works fine but now I need to change the code to take the number of rows and columns as a parameter. As far as I know, this means I need to create the 2D array dynamically:

int** ary = new int*[sizeX]; 

for(int i = 0; i < sizeX; ++i) 
    ary[i] = new int[sizeY]; 

If I create the 2D array this way, the above code to find the row/column breaks. What can I do?

Answers


 int *ary = new int [sizeX * sizeY]; // allocate memory for the 2d array

 for(int i = 0; i < sizeX; ++I)
     for(j = 0; j < sizeY; ++j) 
          ary[i * sizeY + j] = 0;

  // to get the value of collumn c and row r: use ary[c * sizeY + r];

int row = (p - &a[0][0]) / num_columns;
int col = (p - &a[row][0]);

It's a very good idea to stay way from pointer arithmetic. Don't do this! You are essentially subtracting the pointer and divide that number by num_columns, and that number will be random.

If you want to get the row/column of an element, search the array one element at a time.

for(int row=0; row<num_rows; ++row) {
   for(int column=0; column<num_columns; ++column) {
      if (a[row][column] == element) {
         // we got it!
      }
   }
}

Need Your Help

Why my webpage is displayed with question marks, if i switch encoding to UTF-8?

asp.net encoding website globalization

Within the web.config file i have the following, regarding encoding info, since the website is availiale only to Greece.

IV concerns with Authenticated Encryption (GCM mode) for Data at Rest

database authentication encryption cryptography

I am planning to use AES encryption in GCM mode for protecting data at rest for my application.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.