指针,为二维数组分配的动态内存示例

时间:2011-07-06 22:37:08

标签: memory pointers dynamic multidimensional-array

嗯,这是一个完整的样本,但是在最后一次打印后控制台消失了,我不能让它留下来。我还在一些行中包含了一些查询

//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
}

// * ** * **** 非常感谢 * ** * **

1 个答案:

答案 0 :(得分:2)

很容易理解数组上下文中的指针。 因此,如果

int * p
是int的一维数组,那么int ** p将是int的二维数组。换句话说,它是一个包含指向一维数组的指针的数组。

所以

p = (int **) malloc (n * sizeof(int *)); // 
是指向

的指针

和p [i]是指向int的当前指针。