2

For a computer science class i have the following assignment.

Given a 2-dimensional array of doubles containing 128 rows, and 32 columns. The array is stored by placing the columns after eachother in the memory. Complete the following function, which returns the correct element given a pointer to the first element of the array, and some column and row value.

#define N_COLUMNS 32
#define N_ROWS 128
static inline double get_element(const double *A, const int row, const int column)
{...
}

This is what I have so far, but I don't think it's correct.

return *A + column * sizeof(double) + row * sizeof(double);

Can someone help me out?

6
  • Are you sure your teacher is not teaching C? (And even that would be taught poorly it seems.) Commented Jun 24, 2016 at 13:46
  • How is A a two-dimensional array if its type is double* A? Commented Jun 24, 2016 at 13:46
  • * sizeof(double) seems wrong. Commented Jun 24, 2016 at 13:46
  • 2
    Adding something after dereferencing A doesn't seem good, either. Commented Jun 24, 2016 at 13:46
  • 2
    @Codor Flat matrix probably. Commented Jun 24, 2016 at 13:48

3 Answers 3

6

To my understanding, the desired result can be obtained as follows by using pointer arithmetic, assuming zero-based indexing.

return *( A  + ( column * N_ROWS ) + row );

Here sizeof(double) does not need to be used, as A is suitably typed. Adding to it will advance sizeof(double) times the summand.

Sign up to request clarification or add additional context in comments.

Comments

1

try A + column_number * column_size + row_number

remember arrays start at column 0 row 0 for ease of this calculation

Comments

0

The return statement will look like

return *( A + column * N_ROWS  + row );

In fact you have a one-dimensional array that stores N_COLUMNS * N_ROWS elements that is split in groups of N_ROWS elements.

Take into account that there is no need to use the qualifier const with the parameters row and column

These function declarations

static inline double get_element(const double *A, const int row, const int column);

and

static inline double get_element(const double *A, int row, int column);

are equivalent and declare the same one function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.