Louis Vallance
Louis Vallance

Reputation: 13

Extracting a row from a 2-dimensional C++ array

I have a 2D array called resolvedStress which can take m x n rows and columns. I would like to define a new variable called criticalData which is a 1D array containing just one row of resolvedStress. If I want to assign the 4th row to criticalData, would it be correct to write:

float* criticalData = &resolvedStress[4 * n];

I'm new to C++ so I'm not very confident yet!

Upvotes: 0

Views: 1599

Answers (3)

Saravanan
Saravanan

Reputation: 1440

If you want to access fourth row of m X n array, you can access the each row as

  resolvedStress[0] will point to first row of the 2D array.
  resolvedStress[1] will point to second row of the 2D array.

  ...
  resolvedStress[m-1] will point to mth row of the 2D array.

for your case it would be

   float* criticalData = resolvedStress[3];

Upvotes: 0

Kaathe
Kaathe

Reputation: 335

Assuming your array is organised as follows:

[ row0 | row1 | row2 | .... ]

That is, a 1D array containing the rows of the matrix in order, then &resolvedStress[4 * n] will be a pointer to row4 - which is actually the 5th row of the array (gotta love zero indexing).

Upvotes: 0

user2575725
user2575725

Reputation:

Arrays are itself a static pointer, no need to use '&', again as you said you wana point to 4th row so it would be 3 and not 4 as array index starts from 0.

float* criticalData = resolvedStress[3];

Upvotes: 1

Related Questions