开发者

c++ pass auto matrix to function [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

How do I use arrays in C++?

i have a problem. i have to use auto darray(matrix).

const int size_m=10;
const int size_n=10;

void process(int *x)
{
  //i can pass array, all is well, i work as with dynamic allocated array
  for(int i=0;i<size_m;scanf("%d",&x[i]),i++);
}

void input_m(int **x) 
/*
mistake is here, 
a cause of my problem that i'm trying to work  with  matrix allocated in stack(auto matr开发者_如何学Pythonix,local) as with dynamically allocated matrix.
i receive error like this : "cannot convert ‘int [100][100]’ to ‘int**’ in assignment" how should i pass it? 
*/
{
  for(int i=0;i<size_m;i++)
     for(int j=0;j<size_n;j++)
      scanf("%d",&x[i][j]);
}

int main()
{  
  int x[size_m];
  input(x);
  int matr_x[size_m][size_n];
  input_m(matr_x);
  return 0;
}

THANK YOU! it works.. it was so simple, as usual)

    const int sizem=3;
    const int sizen=3;

      void _input(int x[sizem][sizen])
        {

           for(int i=0;i<sizem;i++)
           for(int j=0;j<sizen;x[i][j]=1,j++);
         }

       int main()
         {
            int m=10,n=10;

             int x[sizem][sizen]={{1,2,3},{5,7,4}};

          _input(x);

           for(int i=0;i<sizem;i++)
            { for(int j=0;j<sizen;printf(" %d",x[i][j]),j++);
              puts("");
              }

          puts("");


           return 0;
               }


Your two-dimensional array is incompatible with the function you wrote for fundamental reasons of how memory works in C.

When you write int matrix[size_m][size_n] you are telling the compiler that you want a block of sizeof(int)*size_m*size_n bytes and you intend to store integers in it.

When you write int ** x you are telling the compiler that x is a pointer to a pointer to an integer. If you want to use x as a two-dimensional array, then x should point to not just one pointer, but the first pointer in an array of pointers, i.e. a contiguous region of memory that contains pointers for each row of your matrix. But you don't have any such array of pointers anywhere in the program you posted.

Since you know the dimensions of your matrix at compile time, you can fix this by changing the type of x be int x[size_m][size_n]. Better yet, make a typedef:

typedef int MyMatrix[size_m][size_n];

void input_m(MyMatrix x){ ... }

int main()
{
    MyMatrix matr_x;
    ...
}


First of all, see the answer to this question. Your code should compile if you change void input_m(int **x) to void input_m(int x[size_m][size_n]) (assuming that both size_m and size_n are constants). Note that, as stated in the question that I linked to, "in general, to pass 2D arrays to functions you need to specify the array dimensions for all but the first dimension."

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜