【发布时间】:2011-09-30 00:56:05
【问题描述】:
嗯,这是一个完整的示例,但控制台在最后一次打印后立即消失,我无法让它留下来。还有一些我在某些行中包含的查询
//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("\n\nNumber 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
}
// ********非常感谢 ******
【问题讨论】:
标签: memory pointers dynamic multidimensional-array