본문 바로가기
C 언어

C 언어 동적 배열 (2차원 문자 배열)

by treeCoder 2021. 2. 7.

C 언어에서 동적 배열을 사용하는 방법을 소개한다.

배열 크기를 2배로 증가하는 간단한 버젼은 맨 밑에 있으니 참고바란다.   (에러체크는 생략되어서 간단하다.)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


void exit_if_null(void *ptr, char *msg) {
    if (!ptr) {
        printf("unexpected null pointer: %s\n", msg);
        exit(EXIT_FAILURE);
    }
}

int main() {
    
    char **arr = ( (void *) 0) ; // initialize to NULL
  
    int arrLen = 0;
    
    char input[40];
  
    for(int keepGoing = 1; keepGoing ; ) {
  
      puts("Enter fruit name (type \'end\' to finish.)"); scanf("%39[^\n]", input); while( getchar() != '\n' );
  
      if( input[0]=='e' && input[1]=='n' && input[2]=='d' && input[3]=='\0' ) { 
          keepGoing = 0;  
      } else {
           int found = 0;
           for (int j = 0; j < arrLen && !found; j++) {
               found = (strcmp( input, arr[j] ) == 0);
           }
           if(!found) {
              arr = realloc(arr, (arrLen + 1) * sizeof(*arr));
              arr[arrLen] = (char *) malloc(15);
              exit_if_null(arr[arrLen], "string malloc");
      
              strcpy( arr[arrLen], input );
              arrLen++;
           }
      }
    }
    
    puts("\n*** Your fruits list ***\n");
    for(int i=0; i < arrLen; i++ ) { 
      puts(arr[i]);
    }
    
    for(int i=0; i < arrLen; i++ ) { // free each string
      free(arr[i]);
    }
    free(arr); // free the array
  
    return 0;
}

 

실행 결과는 아래의 그림과 같다.

 

------------------------

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {

  char buf[128];

  char **aos = NULL;
  int maxlen = 0;
  int len = 0;

  while ( fgets(buf, sizeof(buf), stdin) ) {

      if (len == maxlen) {
            if (maxlen == 0) maxlen = 1;
            maxlen *= 2;
            aos = realloc(aos, maxlen * sizeof(*aos));
      }
      
      aos[ len ] = (char *) malloc( 100 );
      strcpy( aos[ len ], buf );
      len++;
      puts( buf );
  }

  return 0;
}

 

 

댓글