使用c中的指针和函数显示2D数组

时间:2015-05-29 19:06:03

标签: c arrays function pointers

stackoverflow的受尊敬成员,                      我是c程序的完整电枢,我想使用指针访问矩阵的元素。我想用点打印矩阵的元素。我已经附加了代码和错误的输出。请帮助我。谢谢你

`
#include<stdio.h>
#include<conio.h>

void print(int **arr, int m, int n)
{
    int i, j;
    for (i = 0; i < m; i++)
    {
      for (j = 0; j < n; j++)
      {
    printf("%d ",*(arr+i*n+j));                   //print the elements of the matrix
    //printf("%d ", *((arr+i*n) + j));
      }
      printf("\n");
    }
}


int main()
{
    int arr[20][20],m,n,c,d;
    clrscr();
    printf("row=\n");
    scanf("%d",&m);
    printf("col=\n");
    scanf("%d",&n);
    for(c=0;c<m;c++)
    {
     for(d=0;d<n;d++)
      {
       scanf("%d",&arr[c][d]);
      }
    }
    for(c=0;c<m;c++)                      //print the matrix without function calling
    {
     for(d=0;d<n;d++)
     {
     printf("%d ",arr[c][d]);
     }
     printf("\n");
    }
    print((int **)arr, m, n);            //print the matrix using function calling
    getch();
    return 0;
}` 

上面的代码产生如下所示的输出

row=
2
col=
3
//elements of the matrix
2
3
4
5
6
7
//print without using function
2 3 4
5 6 7
//print using function"print(int **a,int m,int n)"
2 3 4
0 0 0

使用函数时,我没有得到确切的矩阵值。 注意:应使用print(int ** a,int m,int n)。

2 个答案:

答案 0 :(得分:4)

正如@WhozCraig在他的评论中所说,arr应为int**

int** arr = malloc(sizeof(int*)*m);
int a;
for(a=0;a<m;a++)
    arr[a]=malloc(sizeof(int)*n);
for(c=0;c<m;c++)
{
 for(d=0;d<n;d++)
  {
   scanf("%d", &arr[c][d]); //scanf("%d",arr+c*n+d);
  }
}

注意:未经测试
编辑:malloc not casted

答案 1 :(得分:3)

如果您的编译器支持C99,请尝试以下

#include<stdio.h>
#include<conio.h>

#define N 20

void print(  int m, int n, int ( *a )[n] )
{
    for ( int ( *p )[n] = a; p != a + m; ++p )
    {
        for ( int *q = *p; q != *p + n; ++q ) printf( "%d ", *q );
        printf( "\n" );
    }
}

int main( void )
{
    clrscr();

    int m, n;

    printf( "row = " );
    scanf( "%d", &m );
    printf( "col = " );
    scanf( "%d", &n );

    if ( m > N ) m = N;
    if ( n > N ) n = N;

    int arr[m][n];

    for ( int i = 0; i < m; i++ )
    {
        for ( int j = 0; j < n; j++ )
        {
            scanf( "%d", &arr[i][j] );
        }
    }

    for ( int i = 0; i < m; i++ )
    {
        for ( int j = 0; j < n; j++ ) printf( "%d ", arr[i][j] ); 
        printf( "\n" );
    }


    print( m, n, arr );

    getch();

    return 0;
}` 

否则定义类似

的功能
void print(  int m, int n, int ( *a )[N] )
{
    int ( *p )[N];
    int *q;

    for ( p = a; p != a + m; ++p )
    {
        for ( q = *p; q != *p + n; ++q ) printf( "%d ", *q );
        printf( "\n" );
    }
}