代码中的各种错误。
我已经内联了对更改的评论。我已删除q
和res
。
该代码有两种变体,一种使用单个大小的内存“块”,m * n
另一种使用一个大小的内存块m
来保存m
指向m
其他大小的内存块的指针n
。
m * n
当 m 行中的每一行的 n 为常数时,使用大小有用的单个内存“块”
#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");
}
}