변환문자 서식

자료형 서식 내용 예시
문자형 %c 문자 1개 printf("%c", word);
문자열 %s 문자열 printf("%s", words);
정수형 %d 정수(10진수) printf("%d", number);
실수형 %f 실수 printf("%f", number);

함수

  • 사용자 정의 함수가 밑에 있을 경우
#include <stdio.h>
int add(int x, int y);

int main() {
    int x, y;
    printf("숫자 입력: ");
    sacnf("%d", &x);
    printf("\n 숫자 입력: ");
    sacnf("%d", &y);
    int returnValue = add(x, y);
    printf(returnValue);
    return 0;
}

int add(int x, int y) {
    return x + y;
}
  • 사용자 정의 함수가 위에 있을 경우
#include <stdio.h>

int add(int x, int y) {
    return x + y;
}

int main() {
    int x, y;
    printf("숫자 입력: ");
    sacnf("%d", &x);
    printf("\n 숫자 입력: ");
    sacnf("%d", &y);
    int returnValue = add(x, y);
    printf("%d", returnValue);
    return 0;
}

포인터

  • 메모리 주소를 가리키는 것

  • & : 주소
  • * : 역참조 연산자 - (주소가 가리키는 실제 값)
#include <stdio.h>

int main() {
    int y = 20;
    int* x = &y;

    printf("%p\n", x);
    printf("%p\n", y);

    *x = 30;
    printf("%d\n", x);
    printf("%d", y);
}

이중포인터

  • 주소를 가리키는 또하나의 포인터
#include <stdio.h>

int main() {
    int maxValue = 123;
    int* ptrA = &maxValue;
    int** ptrB = &ptrA;

    printf("%d", *ptrA);
    printf("%d", *(*ptrB));
    // printf("%d", **ptrB); 위와 같은 기능

    printf("%p \n", &ptrA);
    printf("%p", ptrB);
}

예시

  • CallByValue, CallByReference

포인터를 사용하면 메모리 주소값에 있는 데이터를 변경하기 때문에 함수 안에서 이루어진 행위들이 반영된다.

#include <stdio.h>

void swapReference(int* x, int* y) {
    int temp = 0;
    temp = *x;
    *x = *y;
    *y = temp;
}

void swapValue(int x, int y) {
    int temp = 0;
    temp = x;
    x = y;
    y = temp;
}

int main() {
    int x = 100;
    int y = 20;
    swapValue(x, y);
    printf("x = %d, y = %d", x, y);

    printf("\n");
    swapReference(&x, &y);
    printf("x = %d, y = %d", x, y);
    printf("\n");
}

구조체

  • 여러가지 변수의 집합체

변수명 + 변수 별명

typedef struct _listnode{
	int item;
	struct _listnode *next;
} ListNode;	

malloc

  • 동적 메모리 할당
  • 항상 free()를 해야함
  • 해당 사이즈 만큼 할당해줘야함

배열 동적할당

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

int main() {
    int size = 5;
    int* arr = (int*)malloc(sizeof(int) * size);

    arr[0] = 1;
    arr[1] = 2;
    arr[2] = 3;
    arr[3] = 4;
    arr[4] = 5;

    for (int i = 0; i < size; i++) {
        printf("%d", arr[i]);
    }

    free(arr);
}

구조체 동적할당

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

typedef struct _node {
    int item;
    struct _node* next;
} Node;


int main() {
    Node* node = malloc(sizeof(Node));
    node->item = 10;
    Node* nextNode = malloc(sizeof(Node));
    nextNode->item = 30;
    node->next = nextNode;

    while (node != NULL) {
        printf("%d", node->item);
        node = node->next;
    }
    
    free(node);
    free(nextNode);
}

댓글남기기