本教程面向有Java/C#等語言基礎的開發者,通過一系列精簡代碼示例,快速掌握C語言核心語法與底層機制:基本類型、表達式、函數、循環、字符串、指針、動態內存、結構體、函數指針。
static void hello_world(void) {
printf("hello, world\n");
}
static限制文件內可見;printf格式化輸出,\n換行。
static void n_hello_world(int n) {
int i;
for (i = 0; i < n; i++)
printf("hello, world\n");
}
static int w_strlen(const char *str) {
int len = 0;
while (*str++) len++;
return len;
}
const防止誤修改;指針遞增遍歷直到\0。
static void change_str_test(void) {
// char *s1 = "hello"; // 字面量常量區,不可修改
char s1[10] = "hello"; // 棧上數組,可修改
*s1 = 'p';
printf("%s\n", s1); // 輸出 pello
}
static char *reverse(char *str) {
char *left = str;
char *right = str + w_strlen(str) - 1;
while (left < right) {
char tmp = *left; *left = *right; *right = tmp;
left++; right--;
}
return str;
}
static void concat_test(void) {
const char *a = "hello", *b = "world";
int len = w_strlen(a) + w_strlen(b) + 1;
char *buf = malloc(len);
if (!buf) { printf("malloc failed\n"); return; }
char *p = buf;
while (*a) *p++ = *a++;
while (*b) *p++ = *b++;
*p = '\0';
printf("Concatenated: %s\n", buf);
free(buf); // 必須配對釋放
}
原則:誰分配誰釋放;free必須傳入malloc返回的原始地址。
struct customer { char *name; int age; };
static void customer_manager(void) {
struct customer *arr = malloc(2 * sizeof(struct customer));
if (!arr) return;
arr[0] = (struct customer){"wawa", 10};
arr[1] = (struct customer){"tiancai", 30};
for (int i = 0; i < 2; i++)
printf("%s is %d\n", arr[i].name, arr[i].age);
free(arr);
}
static int cmp_asc(int a, int b) { return a - b; }
static int cmp_desc(int a, int b) { return b - a; }
static void sort(int *arr, int n, int (*cmp)(int, int)) {
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-1-i; j++)
if (cmp(arr[j], arr[j+1]) > 0) {
int t = arr[j]; arr[j] = arr[j+1]; arr[j+1] = t;
}
}
static void sort_test(void) {
int a[] = {4,5,3,1,2};
sort(a, 5, cmp_asc); // 1,2,3,4,5
sort(a, 5, cmp_desc); // 5,4,3,2,1
}
函數指針實現策略模式,邏輯與算法解耦。
malloc/free必須配對,否則內存洩漏。const、static限制作用域,減少副作用。