好吧,这里是一个完整的例子,工作,但控制台消失后,最后一次打印,我不能使它停留。还有一些查询,我包括在一些行
//bidimensional array dynamic memory allocation
#include <stdio.h>
#include <stdlib.h>
void main()
{
int **p; // pointer to pointer
int n,m,i,j,k; // n is rows, m is cols, i and j are the indexes of the array, k is going to be like m, but used to print out
do
{
printf("n how many rows?");
scanf ("%d", &n);
}
while (n <= 0);
//为n个元素的数组预订内存,每个元素是一个指向int (int *)的指针
//查询:指向int型类型的指针?它不是一个指向另一个指针的指针吗?它使用**
p = (int **) malloc (n * sizeof(int *)); //
if(p == NULL)
{
printf("Insuficient memory space");
exit( -1);
}
for (i = 0; i < n; i++) // now lets tell each row how many cols it is going to have
{
printf("nnNumber of cols of the row%d :", i+1); // for each row it can be different
scanf("%d", &m); // tell how many cols
p[i] = (int*)malloc(m * sizeof(int)); // we allocate a number of bytes equal to datatype times the number of cols per row
/查询:我不能抓住p[I]因为如果p是指向指针的指针,那么数组符号是什么,我的意思是方括号/
if(p[i] == NULL)
{ printf("Insuficient memory space");
exit(-1);
}
for (j=0;j<m;j++)
{
printf("Element[%d][%d]:", i+1,j+1);
scanf("%d",&p[i][j]); // reading through array notation
}
printf("n elements of row %d:n", i+1);
for (k = 0; k < m; k++)
// printing out array elements through pointer notation
printf("%d ", *(*(p+i)+k));
}
// freeing up memory assigned for each row
for (i = 0; i < n; i++)
free(p[i]);
free(p);// freeing up memory for the pointers matrix
getchar(); // it cannot stop the console from vanishing
fflush(stdin); // neither does this
}
// * * * * * * * * 谢谢 * * * * * *
在数组上下文中很容易理解指针。因此,如果
int * p是int的一维数组,则int ** p将是int的二维数组。也就是说,它是一个包含指向一维数组的指针的数组。
p = (int * *) malloc (n * sizeof (int *));//是指向指针 的指针
和p[i]是指向整型对象的当前指针。