Computer >> 컴퓨터 >  >> 프로그램 작성 >> C 프로그래밍

가변 길이 배열의 사용법을 보여주는 C 프로그램

<시간/>

도서관에서 다양한 작업을 모니터링하고 쿼리하는 도서관 시스템 구축을 담당한다고 가정해 보겠습니다. 이제 다음을 수행하는 세 가지 명령을 구현해야 합니다. -

  • 명령 1을 사용하여 선반 x에 y 페이지가 있는 책의 삽입을 기록할 수 있습니다.

  • 명령 2를 사용하여 선반 x에 있는 y번째 책의 페이지 번호를 인쇄할 수 있습니다.

  • 명령 3을 사용하여 선반 x에 있는 책의 수를 인쇄할 수 있습니다.

명령은 {command type, x, y} 형식의 2D 배열로 제공됩니다. y 값이 없으면 기본값은 0입니다. 주어진 명령의 결과를 인쇄합니다.

따라서 입력이 선반 수 =4, 쿼리 =4, input_arr ={{1, 3, 23}, {1, 4, 128}, {2, 3, 0}, {3, 4, 0과 같으면 }}; 그러면 출력은

23
1
Command 1 inserts a book with 23 pages on shelf 3.
Command 2 inserts a book with 128 pages on shelf 4.
Command 3 prints the page number of book 0 on shelf 3.
Command 4 prints the number of books on shelf 3.

이 문제를 해결하기 위해 다음 단계를 따릅니다. −

  • b :=s 크기의 새 배열
  • p :=s 크기의 새 배열
  • 초기화 i의 경우:=0, i
  • b[i] :=0
  • p[i] :=새 배열
  • loopCount 초기화의 경우:=0, loopCount
  • qtype :=q_array[loopCount, 0]
  • qtype이 1과 같으면 -
    • x :=q_array[loopCount, 1]
    • y :=q_array[loopCount, 2]
    • b[x] :=b[x] + 1
    • p[x] :=p[x]가 가리키는 객체를 할당 해제하고 크기의 포인터를 반환합니다.
    • b[x]
    • p[x, b[x] - 1] =y
  • 그렇지 않으면 qtype이 2와 같을 때 -
    • x :=q_array[loopCount, 1]
    • y :=q_array[loopCount, 2]
    • 인쇄(p[x, y])
  • 그렇지 않으면
    • x :=q_array[loopCount, 1]
    • 인쇄(b[x])
  • b가 null이 아니면 -
    • b가 획득한 메모리 할당 해제
  • 초기화 i의 경우:=0, i
  • p[i]가 null이 아니면 -
    • p[i]가 획득한 메모리 할당 해제
  • p가 null이 아니면 -
    • p가 획득한 메모리 할당 해제
  • 예시

    이해를 돕기 위해 다음 구현을 살펴보겠습니다. −

    #include <stdio.h>
    #include <stdlib.h>
    
    void solve(int s, int q, int q_array[][3])
    {
          int* b;
          int** p;
       b = (int*)malloc(sizeof(int)*s);
       p = (int**)malloc(sizeof(int*)*s);
       for(int i = 0; i < s; i++)
       {
          b[i] = 0;
          p[i] = (int*)malloc(sizeof(int));
       }
       int loopCount;
       for(loopCount = 0; loopCount < q; loopCount++)
       {
          int qtype;
          qtype = q_array[loopCount][0];
          if (qtype == 1)
          {
             int x, y;
             x = q_array[loopCount][1];
                y = q_array[loopCount][2];
             b[x] += 1;
             p[x] = realloc(p[x], b[x]*sizeof(int));
             p[x][b[x] - 1] = y;
          }
          else if (qtype == 2)
          {
             int x, y;
             x = q_array[loopCount][1];
                y = q_array[loopCount][2];
             printf("%d\n", p[x][y]);
          }
          else
          {
             int x;
             x = q_array[loopCount][1];
             printf("%d\n", b[x]);
          }
       }
       if (b)
          free(b);
       for (int i = 0; i < s; i++)
          if (p[i])
             free(p[i]);
       if (p)
          free(p);
    }
    int main() {
       int input_arr[][3] = {{1, 3, 23}, {1, 4, 128}, {2, 3, 0}, {3, 4, 0}};
          solve(4, 4, input_arr);
    }

    입력

    int input_arr[][3] = {{1, 3, 23}, {1, 4, 128}, {2, 3, 0}, {3, 4, 0}};
    solve(4, 4, input_arr);

    출력

    23
    1