06주차 - budoli/8C GitHub Wiki

✅ 예제 1: 값 교환 (Call by Value vs Call by Reference)

#include <stdio.h>
void SwapByValue(int a, int b) {
    int temp = a;
    a = b;
    b = temp;
}
void SwapByReference(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}
int main() {
    int x = 5, y = 10;
    SwapByValue(x, y);
    printf("Value Swap: x=%d, y=%d\n", x, y);

    SwapByReference(&x, &y);
    printf("Reference Swap: x=%d, y=%d\n", x, y);
}

✅ 예제 2: 배열의 모든 값 출력

#include <stdio.h>
void PrintArray(int* arr, int size) {
    for(int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}
int main() {
    int nums[] = {1, 2, 3, 4, 5};
    PrintArray(nums, 5);
}

✅ 예제 3: 포인터를 이용한 값 증가

#include <stdio.h>
void IncreaseByTen(int* p) {
    *p += 10;
}
int main() {
    int num = 7;
    IncreaseByTen(&num);
    printf("Increased Value: %d\n", num);
}

✅ 예제 4: 다중 포인터 (이중 포인터)

#include <stdio.h>
void ChangeValue(int** pp) {
    **pp = 42;
}
int main() {
    int val = 10;
    int* p = &val;
    ChangeValue(&p);
    printf("Changed value: %d\n", val);
}

✅ 예제 5: 배열의 합 구하기

#include <stdio.h>
int ArraySum(int* arr, int size) {
    int sum = 0;
    for(int i = 0; i < size; i++)
        sum += arr[i];
    return sum;
}
int main() {
    int nums[] = {3, 6, 9};
    printf("Sum: %d\n", ArraySum(nums, 3));
}

✅ 예제 6: 포인터로 문자 변경

#include <stdio.h>
void ChangeChar(char* ch) {
    *ch = 'Z';
}
int main() {
    char c = 'A';
    ChangeChar(&c);
    printf("Changed Char: %c\n", c);
}

✅ 예제 7: 포인터 비교

#include <stdio.h>
int main() {
    int a = 5, b = 5;
    int* p1 = &a;
    int* p2 = &b;

    if (p1 == p2)
        printf("Same address\n");
    else
        printf("Different address\n");
}

✅ 예제 8: 포인터를 이용한 배열 초기화

#include <stdio.h>
void InitArray(int* arr, int size, int value) {
    for (int i = 0; i < size; i++) {
        *(arr + i) = value;
    }
}
int main() {
    int arr[5];
    InitArray(arr, 5, 7);
    for (int i = 0; i < 5; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

✅ 예제 9: 함수로 최대값 구하기

#include <stdio.h>
int Max(int* a, int* b) {
    return (*a > *b) ? *a : *b;
}
int main() {
    int x = 30, y = 20;
    printf("Max: %d\n", Max(&x, &y));
}

✅ 예제 10: 포인터로 구조체 멤버 접근

#include <stdio.h>
struct Point {
    int x, y;
};
void MovePoint(struct Point* p, int dx, int dy) {
    p->x += dx;
    p->y += dy;
}
int main() {
    struct Point pt = {2, 3};
    MovePoint(&pt, 5, -1);
    printf("Moved Point: (%d, %d)\n", pt.x, pt.y);
}

⚠️ **GitHub.com Fallback** ⚠️