1

I know, a lot was told about it, yet I couldn't find an explicit reference to what I need.

I need to have a struct member which will point to a two-dimensional array. The array size isn't fixed, each instance of the struct will point to an array with a different size.

I thought about the following way:

struct towDimByPtr
{
    int NumRow;
    int NumCol;
    int* ptr2TwoDim; 
};

Then I'll have globals:

int arr1[30][90];
int arr2[20][10];

towDimByPtr towDim1;
towDimByPtr towDim2;

At init I'll do:

towDim1.ptr2TwoDim = arr1;
towDim1.NumRow = 30;
towDim1.NumCol = 90;
towDim2.ptr2TwoDim = arr2;
towDim2.NumRow = 20;
towDim2.NumCol = 10;

Finally when accessing an element I'll use:

towDim1[curr_row*NumCol + curr_col]

My question: Will this always work.

2
  • C and C++ are row-major order languages, so as long as you keep to that it should work. But I wouldn't recommend using it, as it's quite obfuscating. Commented Feb 19, 2014 at 10:09
  • @JoachimPileborg, Thanks. Could you please provide a reference to that? Commented Feb 19, 2014 at 10:10

1 Answer 1

4

This assignment will not work:

towDim1.ptr2TwoDim = arr1;

arr1 decays into int (*)[90], not int *. You must do this assignment using a pointer to the first element, as in:

towDim1.ptr2TwoDim = &arr1[0][0];

Or, equivalently,

towDim1.ptr2TwoDim = arr1[0];

The same applies to towDim2.ptr2TwoDim = arr2;.

Apart from that, as long as you ensure that curr_row and curr_col are not out of bounds, then yes, it will always work.

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

3 Comments

Thanks Filipe. Could you please provide a reference to the fact that multidimensional arrays are guaranteed to be stored this way?
@Subway Yes, you can see it on wikipedia page about C: en.wikipedia.org/wiki/C_%28programming_language%29#Arrays For a more formal reference, C90 seems to hold this on section F.2.5, "Array storage" (see docs.oracle.com/cd/E19205-01/819-5265/bjbdp/index.html). It says that "C arrays are stored in row-major order; the last subscript in a multidimensional array varies the fastest."
@Subway Just checked on C99 that this is on Section 6.5.2.1, 3rd paragraph: "[...] It follows from this that arrays are stored in row-major order (last subscript varies fastest)".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.