I have older c functions which I want invoke in new cpp program:

// Example of old c function
void c_function(int** x, int r, int c)
{ int i, j;
  for (i = 0; i < r; i++)
       for (j=0; j<c;i++) 
           printf("%i ", *(*(x+i)+j));

// my cpp program, where I would like to invoke c_function

int main(int argc, char *argv[])
  int  r=3, c=2, 
   x[3][2] =
      {00, 01}, 
      {10, 11},
      {20, 21}
  c_function(x, r, c);
  return 0;

This does not work. Error in line c_function(x, r, c):
Conversion of first parameter from 'int [3][2]' to 'int **' impossible. (Sorry, no good translation of foreign language message.)

Question: Is it possible to cast 'int [3][2]' to 'int **' ?

I don't like to use ** pointer in cpp program when [][] for two dimensional arrays is possible.

Thanks a lot for your advice.

8 Years
Discussion Span
Last Post by yap

The problem is that an array declared as: [B]int[/B] a[ 42 ][ 17 ]; is not the same as [B]int[/B] *a[ 42 ]; The first is a 2D array of 714 (42 x 17) ints.
The second is a 1D array of 42 pointers to int.

The c_function() is looking for something like the second, but you are trying to give it something like the first.

[edit] It is a vagary of the C language that lets you treat pointers like arrays, so however you define it, you can reference a specific int as: a[ 10 ][ 4 ] For the first type, it is just a simple multiplication and one dereference to index the element: *(a + (10 * 42) + 4) For the second type, it is two dereferences: *(*(a + 10) + 4) Hope this helps.


Casting won't change the type of thing found found in the array. It will only make the program look at it as if it were a different type -- which in this case is not the correct type.

You can either fix the original function to take the correct type, or you can fix the thing you are passing to it to be the correct type.

BTW, I presume it is a typo at the end of line 6 to i++ instead of j++ Hope this helps.


yes, its a typo, should have been j.
Now I am convinced that the problem can't be solved with simple cast. What I can do is 1) Changing old c-functions to modern cpp syntax, where the problem with [][const x] still exists. This is also an expensive way. 2) I introduce ** syntax for 2d arrays in cpp program what would allow to use old c functions. Than I need to allocate a vector (first *) and the pointers to further allocated vectors (second *) are stored in first vector. I think this will be the best solution.
Thanks to everybody who has helped me.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.