C语言实战

以下是C语言实战中常见的应用场景和解决方案,涵盖基础到进阶内容:

变量与数据类型

整型、浮点型、字符型变量的声明与初始化:

复制代码
int count = 10;
float price = 9.99f;
char grade = 'A';

结构体和联合体的使用:

复制代码
struct Point {
    int x;
    int y;
};
union Data {
    int i;
    float f;
};

内存管理

动态内存分配与释放:

复制代码
int *arr = (int*)malloc(10 * sizeof(int));
free(arr);

内存操作函数示例:

复制代码
char src[50] = "Hello";
char dest[50];
memcpy(dest, src, strlen(src)+1);

文件操作

文本文件读写:

复制代码
FILE *f = fopen("data.txt", "w");
fprintf(f, "%d %f", 100, 3.14);
fclose(f);

二进制文件处理:

复制代码
struct Record r;
FILE *bin = fopen("data.bin", "rb");
fread(&r, sizeof(struct Record), 1, bin);

数据结构实现

链表节点定义:

复制代码
typedef struct Node {
    int data;
    struct Node* next;
} Node;

栈的基本操作:

复制代码
#define MAX 100
int stack[MAX];
int top = -1;

void push(int item) {
    if(top >= MAX-1) return;
    stack[++top] = item;
}

算法实现

快速排序示例:

复制代码
void quickSort(int arr[], int left, int right) {
    if(left >= right) return;
    int i = left, j = right;
    int pivot = arr[(left+right)/2];
    while(i <= j) {
        while(arr[i] < pivot) i++;
        while(arr[j] > pivot) j--;
        if(i <= j) {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            i++; j--;
        }
    }
    quickSort(arr, left, j);
    quickSort(arr, i, right);
}

多线程编程

POSIX线程创建:

复制代码
#include <pthread.h>
void* thread_func(void* arg) {
    printf("Thread running\n");
    return NULL;
}

pthread_t tid;
pthread_create(&tid, NULL, thread_func, NULL);
pthread_join(tid, NULL);

网络编程

TCP客户端示例:

复制代码
#include <sys/socket.h>
#include <netinet/in.h>

int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr = {
    .sin_family = AF_INET,
    .sin_port = htons(8080),
    .sin_addr.s_addr = inet_addr("127.0.0.1")
};
connect(sock, (struct sockaddr*)&addr, sizeof(addr));

调试技巧

使用gdb基本命令:

复制代码
gcc -g program.c -o program
gdb ./program
break main
run
print variable

性能优化

循环展开示例:

复制代码
// 原始循环
for(int i=0; i<100; i++) { sum += arr[i]; }

// 展开4次
for(int i=0; i<100; i+=4) {
    sum += arr[i];
    sum += arr[i+1];
    sum += arr[i+2];
    sum += arr[i+3];
}
相关推荐
伊玛目的门徒4 小时前
试用leetcode之典中典 二数之和问题
java·算法·leetcode
Jerry5 小时前
LeetCode 226. 翻转二叉树
算法
想做小南娘,发现自己是女生喵6 小时前
【无标题】
数据结构·算法
Kx_Triumphs8 小时前
HDU4348 To the moon(主席树区间修改模板)
算法·题解
旖-旎8 小时前
《LeetCode647 回文子串 || LeetCode 5 最长回文子串》
c++·算法·leetcode·动态规划·哈希算法
轻颂呀9 小时前
约瑟夫环问题
算法
科技大视界11 小时前
投资AI项目,传统尽调不够用了——李章虎律师拆解算法、数据、算力三大雷区
人工智能·算法·数据挖掘
郝学胜-神的一滴11 小时前
算法实战:最小k个数——大顶堆的优雅解法
开发语言·数据结构·c++·python·程序人生·算法·排序算法
Irissgwe11 小时前
算法滑动窗口
数据结构·算法