C语言作为一种历史悠久且功能强大的编程语言,至今仍被广泛应用于系统编程、嵌入式系统、游戏开发等领域。为了帮助你更好地掌握C语言编程,以下是从基础到进阶的50个实用实例,涵盖了C语言编程的多个方面。

实例1:C语言的简单“Hello World”

#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}

这是一个最基础的C语言程序,用于输出“Hello, World!”到控制台。

实例2:变量和赋值

#include <stdio.h>

int main() {
    int a = 5;
    printf("The value of a is: %d\n", a);
    return 0;
}

演示了如何声明一个整型变量a并给它赋值。

实例3:数据类型转换

#include <stdio.h>

int main() {
    int a = 10;
    float b = (float)a;
    printf("The value of b is: %f\n", b);
    return 0;
}

展示了如何将整型变量转换为浮点型。

实例4:运算符

#include <stdio.h>

int main() {
    int x = 10, y = 5;
    printf("Sum: %d\n", x + y);
    printf("Difference: %d\n", x - y);
    printf("Product: %d\n", x * y);
    printf("Quotient: %d\n", x / y);
    printf("Remainder: %d\n", x % y);
    return 0;
}

这里展示了基本的算术运算符的使用。

实例5:条件语句

#include <stdio.h>

int main() {
    int age = 18;
    if (age >= 18) {
        printf("You are an adult.\n");
    } else {
        printf("You are not an adult.\n");
    }
    return 0;
}

使用if-else语句来判断年龄。

实例6:循环语句

#include <stdio.h>

int main() {
    int i;
    for (i = 1; i <= 5; i++) {
        printf("Count %d\n", i);
    }
    return 0;
}

使用for循环来打印从1到5的数字。

实例7:数组操作

#include <stdio.h>

int main() {
    int numbers[5] = {1, 2, 3, 4, 5};
    int sum = 0;
    for (int i = 0; i < 5; i++) {
        sum += numbers[i];
    }
    printf("Sum of array elements: %d\n", sum);
    return 0;
}

演示了如何声明、初始化和使用数组。

实例8:指针基础

#include <stdio.h>

int main() {
    int a = 10;
    int *ptr = &a;
    printf("Value of a: %d\n", a);
    printf("Address of a: %p\n", (void *)&a);
    printf("Value pointed by ptr: %d\n", *ptr);
    return 0;
}

介绍了指针的概念,以及如何使用指针访问变量。

实例9:结构体

#include <stdio.h>

typedef struct {
    char name[50];
    int age;
    float salary;
} Employee;

int main() {
    Employee emp;
    strcpy(emp.name, "John Doe");
    emp.age = 30;
    emp.salary = 50000.0;
    printf("Name: %s\n", emp.name);
    printf("Age: %d\n", emp.age);
    printf("Salary: %.2f\n", emp.salary);
    return 0;
}

展示了如何定义和使用结构体。

实例10:函数定义和调用

#include <stdio.h>

void greet() {
    printf("Hello, World!\n");
}

int main() {
    greet();
    return 0;
}

这是一个简单的函数定义和调用的例子。

实例11:递归函数

#include <stdio.h>

int factorial(int n) {
    if (n <= 1)
        return 1;
    return n * factorial(n - 1);
}

int main() {
    int num = 5;
    printf("Factorial of %d is %d\n", num, factorial(num));
    return 0;
}

递归函数用于计算阶乘。

实例12:指针和数组

#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 arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    printArray(arr, size);
    return 0;
}

这个例子展示了如何通过指针操作数组。

实例13:字符串操作

#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "Hello";
    char str2[] = "World";
    char str3[50];
    strcpy(str3, str1);
    strcat(str3, str2);
    printf("Concatenated string: %s\n", str3);
    return 0;
}

字符串的复制和连接操作。

实例14:文件操作

#include <stdio.h>

int main() {
    FILE *file;
    char filename[] = "example.txt";

    file = fopen(filename, "w");
    fprintf(file, "This is a test.\n");
    fclose(file);

    file = fopen(filename, "r");
    char ch;
    while ((ch = fgetc(file)) != EOF) {
        putchar(ch);
    }
    fclose(file);
    return 0;
}

文件读取和写入的基本操作。

实例15:结构体指针

#include <stdio.h>

typedef struct {
    int x;
    int y;
} Point;

void printPoint(const Point *p) {
    printf("Point coordinates: (%d, %d)\n", p->x, p->y);
}

int main() {
    Point p = {1, 2};
    printPoint(&p);
    return 0;
}

使用结构体指针来访问结构体成员。

实例16:动态内存分配

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

int main() {
    int *ptr = (int *)malloc(10 * sizeof(int));
    if (ptr == NULL) {
        printf("Memory allocation failed.\n");
        return 1;
    }

    for (int i = 0; i < 10; i++) {
        ptr[i] = i;
    }

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

    free(ptr);
    return 0;
}

演示了如何动态分配和释放内存。

实例17:位操作

#include <stdio.h>

int main() {
    int a = 5; // 0000 0101
    int b = 3; // 0000 0011

    printf("a AND b: %d\n", a & b); // 0000 0001
    printf("a OR b: %d\n", a | b); // 0000 0111
    printf("a XOR b: %d\n", a ^ b); // 0000 0100
    printf("a NOT b: %d\n", ~b);   // 1111 1100

    return 0;
}

位操作示例,包括AND、OR、XOR和NOT。

实例18:枚举类型

#include <stdio.h>

enum Weekday {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday
};

int main() {
    enum Weekday today = Wednesday;
    printf("Today is: %d\n", today);
    return 0;
}

枚举类型的定义和用法。

实例19:联合体

#include <stdio.h>

typedef union {
    int i;
    float f;
    char c[4];
} Data;

int main() {
    Data d;
    d.i = 10;
    printf("Value of d.i: %d\n", d.i);

    d.f = 3.14;
    printf("Value of d.f: %f\n", d.f);

    for (int i = 0; i < 4; i++) {
        printf("Value of d.c[%d]: %c\n", i, d.c[i]);
    }
    return 0;
}

联合体允许存储不同类型的数据在同一内存位置。

实例20:错误处理

#include <stdio.h>

int divide(int a, int b) {
    if (b == 0) {
        fprintf(stderr, "Error: Division by zero.\n");
        return -1;
    }
    return a / b;
}

int main() {
    int result = divide(10, 0);
    if (result == -1) {
        return 1; // Error occurred
    }
    printf("Result: %d\n", result);
    return 0;
}

如何处理函数调用中的错误。

实例21:宏定义

#include <stdio.h>

#define MAX 5
#define square(x) (x) * (x)

int main() {
    int a = 3;
    printf("Square of %d is %d\n", a, square(a));
    return 0;
}

宏定义的使用示例。

实例22:预处理器指令

#include <stdio.h>

#if defined(__linux__)
    #define OS "Linux"
#elif defined(__APPLE__)
    #define OS "MacOS"
#else
    #define OS "Windows"
#endif

int main() {
    printf("The operating system is: %s\n", OS);
    return 0;
}

预处理器指令的使用,根据不同的编译环境设置不同的宏值。

实例23:结构体数组和指针

#include <stdio.h>

typedef struct {
    int x;
    int y;
} Point;

void printPointArray(const Point *arr, int size) {
    for (int i = 0; i < size; i++) {
        printf("Point %d coordinates: (%d, %d)\n", i, arr[i].x, arr[i].y);
    }
}

int main() {
    Point arr[] = {{1, 2}, {3, 4}, {5, 6}};
    int size = sizeof(arr) / sizeof(arr[0]);
    printPointArray(arr, size);
    return 0;
}

使用结构体指针和数组。

实例24:函数指针

#include <stdio.h>

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

int main() {
    int (*fnPtr)(int, int) = add;
    printf("Result: %d\n", fnPtr(3, 4));
    return 0;
}

函数指针的声明和使用。

实例25:结构体和函数指针

#include <stdio.h>

typedef struct {
    int x;
    int y;
} Point;

void printPoint(const Point *p) {
    printf("Point coordinates: (%d, %d)\n", p->x, p->y);
}

int main() {
    Point p = {1, 2};
    printPoint(&p);
    return 0;
}

结构体和函数指针的结合使用。

实例26:递归和栈溢出

#include <stdio.h>

void recursiveFunction() {
    recursiveFunction(); // This will cause a stack overflow
}

int main() {
    // This will cause the program to crash
    recursiveFunction();
    return 0;
}

递归函数的例子,可能会导致栈溢出。

实例27:动态链接库

#include <stdio.h>
#include <dlfcn.h>

int main() {
    void *handle = dlopen("libexample.so", RTLD_LAZY);
    if (!handle) {
        fprintf(stderr, "Error opening library: %s\n", dlerror());
        return 1;
    }

    int (*add)(int, int);
    *(void **)(&add) = dlsym(handle, "add");
    if (!add) {
        fprintf(stderr, "Error loading symbol: %s\n", dlerror());
        dlclose(handle);
        return 1;
    }

    printf("Result: %d\n", add(3, 4));
    dlclose(handle);
    return 0;
}

动态链接库的使用示例。

实例28:线程和互斥锁

#include <stdio.h>
#include <pthread.h>

pthread_mutex_t lock;

void *threadFunction(void *arg) {
    pthread_mutex_lock(&lock);
    printf("Thread %d is running\n", *(int *)arg);
    pthread_mutex_unlock(&lock);
    return NULL;
}

int main() {
    pthread_mutex_init(&lock, NULL);
    pthread_t threads[2];
    int arg1 = 1, arg2 = 2;

    pthread_create(&threads[0], NULL, threadFunction, &arg1);
    pthread_create(&threads[1], NULL, threadFunction, &arg2);

    pthread_join(threads[0], NULL);
    pthread_join(threads[1], NULL);

    pthread_mutex_destroy(&lock);
    return 0;
}

线程和互斥锁的使用,以防止数据竞争。

实例29:信号量和条件变量

#include <stdio.h>
#include <pthread.h>

pthread_mutex_t lock;
pthread_cond_t cond;
int counter = 0;

void producer() {
    pthread_mutex_lock(&lock);
    counter++;
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&lock);
}

void consumer() {
    pthread_mutex_lock(&lock);
    while (counter == 0) {
        pthread_cond_wait(&cond, &lock);
    }
    counter--;
    pthread_mutex_unlock(&lock);
}

int main() {
    pthread_mutex_init(&lock, NULL);
    pthread_cond_init(&cond, NULL);

    pthread_t prod, cons;
    pthread_create(&prod, NULL, producer, NULL);
    pthread_create(&cons, NULL, consumer, NULL);

    pthread_join(prod, NULL);
    pthread_join(cons, NULL);

    pthread_mutex_destroy(&lock);
    pthread_cond_destroy(&cond);
    return 0;
}

信号量和条件变量的使用,实现生产者-消费者问题。

实例30:网络编程

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>

#define PORT 8080

int main() {
    int server_fd, new_socket;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);

    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }

    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);

    if (bind(server_fd, (struct sockaddr *)&address, sizeof(address))<0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    if (listen(server_fd, 3) < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }

    if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) {
        perror("accept");
        exit(EXIT_FAILURE);
    }

    char buffer[1024] = {0};
    read(new_socket, buffer, 1024);
    printf("Client: %s\n", buffer);

    send(new_socket, "Hello from server", 18, 0);

    close(new_socket);
    close(server_fd);
    return 0;
}

简单的TCP服务器和客户端示例。

实例31:多线程并发

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

int counter = 0;

void *threadFunction(void *arg) {
    for (int i = 0; i < 1000; i++) {
        __atomic_add_fetch(&counter, 1, __ATOMIC_SEQ_CST);
    }
    return NULL;
}

int main() {
    pthread_t threads[10];
    for (int i = 0; i < 10; i++) {
        pthread_create(&threads[i], NULL, threadFunction, NULL);
    }

    for (int i = 0; i < 10; i++) {
        pthread_join(threads[i], NULL);
    }

    printf("Counter: %d\n", counter);
    return 0;
}

使用原子操作和多线程实现线程安全的计数。

实例32:文件系统操作

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

#define FILENAME "example.txt"

int main() {
    FILE *file = fopen(FILENAME, "w");
    if (file == NULL) {
        perror("File open failed");
        return 1;
    }

    fprintf(file, "This is a test file.\n");
    fclose(file);

    struct stat st = {0};
    if (stat(FILENAME, &st) == -1) {
        perror("File stat failed");
        return 1;
    }

    printf("File size: %ld bytes\n", st.st_size);

    remove(FILENAME);
    return 0;
}

文件创建、读取、状态获取和删除。

实例33:进程间通信(IPC)

”`c #include #include #include #include #include

int main() {

key_t key = 1234;
int shmid;
char *data;

if ((shmid = shmget(key, 1024, 0666 | IPC_CREAT)) == -1) {
    perror("shmget