Skip to content

Instantly share code, notes, and snippets.

@Rockheung
Last active January 12, 2019 12:00
Show Gist options
  • Save Rockheung/e4c254dae3df5284ecd17f756ed3785d to your computer and use it in GitHub Desktop.
Save Rockheung/e4c254dae3df5284ecd17f756ed3785d to your computer and use it in GitHub Desktop.

Data Structure Chapter 2 - Array

배열

  • 형태: array[index]

  • 다차원 배열 빠르게 시각화하기: a[3][5][7]와 같은 배열의 경우 7, 5, 3 순으로 가로, 세로, 깊이 방향으로 생각하면 된다.

  • 예제 2-1, 자료형에 대한 메모리 할당 크기 확인하기

#include <stdio.h>

int main() {
    char c, c_array[100];
    int i, i_array[100];
    short s, s_array[100];
    float f, f_array[100];
    long l, l_array[100];

    printf("\n char c: %d \t char c_array: %4d", sizeof(c), sizeof(c_array));
    printf("\n char i: %d \t char i_array: %4d", sizeof(i), sizeof(i_array));
    printf("\n char s: %d \t char s_array: %4d", sizeof(s), sizeof(s_array));
    printf("\n char f: %d \t char f_array: %4d", sizeof(f), sizeof(f_array));
    printf("\n char l: %d \t char l_array: %4d", sizeof(l), sizeof(l_array));

    return 0;
}
$ gcc 2-1.c -o 2-1.out && ./2-1.out

 char c: 1 	 char c_array:  100
 char i: 4 	 char i_array:  400
 char s: 2 	 char s_array:  200
 char f: 4 	 char f_array:  400
 char l: 8 	 char l_array:  800
  • 예제 2-3, 입력한 숫자를 구구단으로 출력하기
#include <stdio.h>

int main() {

    int i, n = 0;
    int multiply[9];

    do {
        printf("\n1~9의 정수를 입력하세요 : ");
        scanf("%d", &n);
    } while (n<0 || n>9);

    printf("\n");
    for (i=0; i<9; i++){
        multiply[i] = n*(i+1);
        printf(" %d * %d = %d \n", n, (i+1), multiply[i]);
    }

    return 0;
}
$ gcc 2-3.c -o 2-3.out && ./2-3.out

1~9의 정수를 입력하세요 : 10

1~9의 정수를 입력하세요 : 9

 9 * 1 = 9 
 9 * 2 = 18 
 9 * 3 = 27 
 9 * 4 = 36 
 9 * 5 = 45 
 9 * 6 = 54 
 9 * 7 = 63 
 9 * 8 = 72 
 9 * 9 = 81 
  • 예제 2-5, 입력한 문자열의 길이
#include <stdio.h>

int main() {

    int i, length = 0;
    char str[50];
    printf("\n문자열을 입력하세요 : ");
    gets(str);
    printf("\n입력된 문자열은 \n \"");
    for ( i=0; str[i]; i++) {
        printf("%c", str[i]);
        length += 1;
    }

    printf("\" \n입니다.");
    printf("\n\n입력된 문자열의 길이 = %d \n", length);

    return 0;
}
$ gcc 2-5.c -o 2-5.out && ./2-5.out
2-5.c: In function ‘main’:
2-5.c:8:5: warning: implicit declaration of function ‘gets’; did you mean ‘fgets’? [-Wimplicit-function-declaration]
     gets(str);
     ^~~~
     fgets
/tmp/cclBoqGE.o: In function `main':
2-5.c:(.text+0x3c): warning: the `gets' function is dangerous and should not be used.

문자열을 입력하세요 : 안녕 젠장할 문자열아

입력된 문자열은 
 "안녕 젠장할 문자열아" 
입니다.

입력된 문자열의 길이 = 29 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment