【问题标题】:pointers, dynamic memo allocat for bidimensional arrays A sample指针,为二维数组分配的动态内存示例
【发布时间】: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


    【解决方案1】:

    数组上下文中的指针很容易理解。 所以如果

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

    所以

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

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

    【讨论】:

      猜你喜欢
      • 2017-11-02
      • 2015-11-04
      • 1970-01-01
      • 2020-07-11
      • 1970-01-01
      • 2013-10-04
      • 1970-01-01
      • 2014-07-19
      相关资源
      最近更新 更多