代码中的各种错误。
我已将这些更改的评论内联。我已删除q
和res
。
有两种使用的大小m * n
的存储器和的大小m
的存储器的另一使用一个块的单个“块”来保持m
指针的大小n
的存储器m
其它块的代码,一个的两个变体。
使用的尺寸的存储器中的单个“块” m * n
当n是为每个使用的尺寸的存储器中的一个块中的m条线
#include <stdio.h>
#include <stdlib.h>
void main()
{
int i,j,m,n;
/* Changed to *p. Instead of an array of arrays
you'll use a single block of memory */
int *p;
printf("Enter the number of rows and columns:");
scanf("%d %d",&m,&n);
/* m rows and n columns = m * n "cells" */
p = (int*) malloc(m * n * sizeof(int));
printf("Enter the elements of the matrix\n");
for (i=0;i<m;i++)
{
for (j=0;j<n;j++)
{
/* the element at row i and column j is the (i * m) + j
element of the block of memory, so p + (i*m) + j .
It's already an address to memory, so you don't need the & */
scanf("%d", (p + (i*m) + j));
}
}
for (i=0;i<m;i++)
{
for (j=0;j<n;j++)
{
/* same as before, but this time you have
to dereference the address */
printf("%d ", *(p + (i*m) + j));
}
printf("\n");
}
}
的恒定有用m
保持m
指向m
其他区块的内存大小n
当n是变量对于每个m行的( “锯齿状” 阵列)
#include<stdio.h>
#include<stdlib.h>
void main()
{
int i,j,m,n;
int **p;
printf("Enter the number of rows and columns:");
scanf("%d %d",&m,&n);
/* We will have m "rows", each element a ptr to a full row of n columns
Note that each element has size == sizeof(int*) because it's a ptr
to an array of int */
p = (int**) malloc(m * sizeof(int*));
printf("Enter the elements of the matrix\n");
for (i=0;i<m;i++)
{
/* For each row we have to malloc the space for the
columns (elements) */
*(p + i) = (int*)malloc(n * sizeof(int));
for (j=0;j<n;j++)
{
/* Compare the reference to the one before, note
that we first dereference *(p + i) to get the
ptr of the i row and then to this ptr we add
the column index */
scanf("%d", *(p + i) + j);
}
}
for (i=0;i<m;i++)
{
for (j=0;j<n;j++)
{
/* Note the double dereferencing, first to the address
of the row of data
and then to the exact column */
printf("%d ", *(*(p + i) + j));
}
printf("\n");
}
}
scanf()的不忽略回车 –