2011-07-06 5 views
0

글쎄, 여기에 전체 샘플이 있지만 마지막으로 인쇄 한 직후에 콘솔이 사라지고 그다지 머물러 있습니다. 또한 I는 어떤 라인에 포함 몇 쿼리포인터, 2 차원 배열의 동적 메모 allocat 샘플

//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에 대한 포인터? 그것은 포인터에 포인터가 wouldnt? 그것은 **

 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는 포인터에 대한 포인터 인 경우 [내가] 때문에, 그 배열 표기법은 무엇입니까 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 
} 

// * ** * ****덕분에 많은* ** * **

답변

2

배열의 문맥에서 포인터를 쉽게 이해할 수 있습니다.

int * p
이 int의 1 차원 배열 인 경우 int ** p는 int의 2 차원 배열입니다. 다시 말해, 1 차원 배열에 대한 포인터를 포함하는 배열입니다.

너무

p = (int **) malloc (n * sizeof(int *)); //
포인터

및 P [I]에 대한 포인터이다 INT 전류 포인터이다.

관련 문제