-3

I have a two dimensional array like this:

ptr = (int **) malloc(size);

for (i = 0; i < len; i++) {
    ptr[i] = (int *) malloc(size);
}

Is there a simple way to create a int *intPtr to that array such that I can access the values in row major order?

e.g.: if ptr points to an n*n array, I want to get the first item of the second column like this: *(intPtr + n)

I need this conversion to pass my two dimensional array to a cuda kernel, I want to avoid to pass a two dimensional array to that kernel because that seems to be quiet complicated.

user3648650
  • 37
  • 1
  • 7
  • flatten your 2D array into a 1D array. That's not hard to do since your dimension (`size`) is constant. Then pass the 1D array to cuda, which is easy to do. You can use subscript arithmetic on the 1D array to reference the 2D array elements if you want. – Robert Crovella May 18 '14 at 00:16
  • Can you clarify what you are asking? In row-major ordering, `*(ptr + n)` is a pointer to the first element of the second row. Did you mean that you want to "view" the array as if it were column-major, and have a pointer to the first element of the second column, which can be incremented to get other elements in the column? – M.M May 18 '14 at 00:22
  • When you say "the first item of the second column" do you mean just a single int, or do you mean a pointer via which you can access many ints, starting with the first? – M.M May 18 '14 at 00:23
  • Sorry, I accidentally wrote "first item of the second column" but I actually meant the first item of the second row. – user3648650 May 18 '14 at 22:53

1 Answers1

3

No. if you had allocated a true 2d array of ints:

int a[size][size];

then the answer might be yes though the result is not portable. Refer to this article for more array type punning information.

But accessing an element in a row of your array requires explicitly dereferencing a pointer.

Community
  • 1
  • 1
Gene
  • 46,253
  • 4
  • 58
  • 96