首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C語言快速入門實戰:從Hello World到函數指針、動態內存、結構體

     編輯:關於C語言

C語言快速入門實戰指南:核心特性一網打盡

本教程面向有Java/C#等語言基礎的開發者,通過一系列精簡代碼示例,快速掌握C語言核心語法與底層機制:基本類型、表達式、函數、循環、字符串、指針、動態內存、結構體、函數指針。

1. 最小化Hello World

static void hello_world(void) {
    printf("hello, world\n");
}

static限制文件內可見;printf格式化輸出,\n換行。

2. 循環與分支 (C89風格:變量聲明在塊開頭)

static void n_hello_world(int n) {
    int i;
    for (i = 0; i < n; i++)
        printf("hello, world\n");
}

3. 字符串長度計算 (指針版)

static int w_strlen(const char *str) {
    int len = 0;
    while (*str++) len++;
    return len;
}

const防止誤修改;指針遞增遍歷直到\0。

4. 字符串存儲區別

static void change_str_test(void) {
    // char *s1 = "hello"; // 字面量常量區,不可修改
    char s1[10] = "hello"; // 棧上數組,可修改
    *s1 = 'p';
    printf("%s\n", s1); // 輸出 pello
}

5. 指針操作:原地反轉字符串

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;
}

6. 動態內存管理:字符串拼接

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返回的原始地址。

7. 結構體與動態數組

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);
}

8. 函數指針:通用冒泡排序

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
}

函數指針實現策略模式,邏輯與算法解耦。

💡 核心心法

  1. C語言雖小,指針與內存模型是靈魂,必須動手練習。
  2. 無GC,malloc/free必須配對,否則內存洩漏。
  3. 善用const、static限制作用域,減少副作用。
  4. 函數指針是C語言實現多態與回調的基石。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved