✅ 예제 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);
}
#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);
}
#include <stdio.h>
void IncreaseByTen(int* p) {
*p += 10;
}
int main() {
int num = 7;
IncreaseByTen(&num);
printf("Increased Value: %d\n", num);
}
#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);
}
#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));
}
#include <stdio.h>
void ChangeChar(char* ch) {
*ch = 'Z';
}
int main() {
char c = 'A';
ChangeChar(&c);
printf("Changed Char: %c\n", c);
}
#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");
}
#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");
}
#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));
}
#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);
}