代碼中的各種錯誤。
我已將這些更改的評論內聯。我已刪除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()的不忽略回車 –