打印使用指针方阵 [英] Print a square matrix using pointers

查看:162
本文介绍了打印使用指针方阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经浏览到的关于指针和矩阵previously回答问题,但在这些情况下,矩阵被视为指针的指针。不过,我想创建一个读取使用一个简单的指针和它打印另一个函数矩阵的功能。
这是我的code,读取功能似乎正常工作,但程序崩溃在打印部分。如果我删除*从printf语句的程序工作(即,它打印的数字从4至4-我想这是正常的,因为一个int存储在4个字节)。

 无效readm为(int * P,INT N)
{
 P =(INT *)malloc的(的sizeof(int)的* N * N);
 的for(int i = 0; I< n * n的;我++)
        scanf函数(%d个P + I);
}无效printm为(int * P,INT N)
{
  的for(int i = 0; I< N;我++)
  {
    对于(INT J = 0; J< N; J ++)
        的printf(%d个*(P +(I * N)+ J));
      的printf(\\ n);
  }
}


解决方案

在你有这条线问题 readm 功能:

  P =(INT *)malloc的(的sizeof(int)的* N * N);

在这里,你只分配给您的本地副本的指针。你打电话时 readm 使用变量的的改变。

您需要通过引用传递指针:

 无效readm(INT ** P,INT N)/ *注意指针到指针`p` * /
{
    * P =的malloc(sizeof的(INT)* N * N); / *注意`p`的指针解引用* /
    的for(int i = 0; I< n * n的;我++)
        scanf函数(%D,* P + I); / *注意`p`的指针解引用* /
}

您必须再使用调用函数运算符的地址的:

  INT * P;
readm(安培; P,X); / *注意使用地址的运算符* /

I've browsed to previously answered questions regarding pointers and matrices, but in these cases the matrices were seen as pointers to pointers. However, I am trying to create a function which read a matrix using a simple pointer and another function which prints it. This is my code, the read functions seems to work properly, but the program crashes at the printing part. If I remove the "*" from the printf statement the program works(i.e. it prints numbers from 4 to 4- I suppose this is alright, since an int is stored on 4 bytes).

void readm(int *p,int n)
{
 p=(int *)malloc(sizeof(int)*n*n);
 for(int i=0;i<n*n;i++)
        scanf("%d",p+i);
}

void printm(int *p,int n)
{
  for(int i=0;i<n;i++)
  {
    for(int j=0;j<n;j++)
        printf("%d ",*(p+(i*n)+j));
      printf("\n");
  }
}

解决方案

In the readm function you have a problem with this line:

p=(int *)malloc(sizeof(int)*n*n);

Here you assign only to your local copy of the pointer. The variable you use when calling readm will not be changed.

You need to pass the pointer "by reference":

void readm(int **p,int n)  /* Note pointer-to-pointer for `p` */
{
    *p=malloc(sizeof(int)*n*n);  /* Note pointer-dereference of `p` */
    for(int i=0;i<n*n;i++)
        scanf("%d",*p+i);  /* Note pointer-dereference of `p` */
}

You then have to call the function using the address-of operator:

int *p;
readm(&p, X);  /* Note use of address-of operator */

这篇关于打印使用指针方阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆