下面是我整理的一些偏难的C语言程序,希望对学C语言的新手们有所帮助。
1. 正则表达式匹配
```c
#include <stdio.h>
#include <regex.h>
int main() {
regex_t regex;
int ret;
char source[] = "This is a sample text.";
ret = regcomp(®ex, "sample", 0); // 编译正则表达式
ret = regexec(®ex, source, 0, NULL, 0); // 执行正则表达式匹配
if (!ret) {
printf("Match found.\n"); // 匹配成功
} else if (ret == REG_NOMATCH) {
printf("No match found.\n"); // 未匹配成功
}
regfree(®ex); // 释放正则表达式资源
return 0;
}
```
2. 多线程编程
```c
#include <stdio.h>
#include <pthread.h>
void *myThread(void *arg) {
printf("This is a thread.\n");
return NULL;
}
int main() {
pthread_t thread;
pthread_create(&thread, NULL, myThread, NULL); // 创建线程
pthread_join(thread, NULL); // 等待线程结束
printf("Main thread.\n");
return 0;
}
```
3. 动态内存分配
```c
#include <stdio.h>
#include <stdlib.h>
int main() {
int *array = (int *) malloc(5 * sizeof(int)); // 分配动态内存
if (array == NULL) {
printf("Memory allocation failed.\n"); // 内存分配失败
return 1;
}
for (int i = 0; i < 5; i++) {
array[i] = i; // 初始化数组
}
for (int i = 0; i < 5; i++) {
printf("%d ", array[i]); // 打印数组
}
free(array); // 释放动态内存
return 0;
}
```
4. 文件操作
```c
#include <stdio.h>
int main() {
char ch;
FILE *file = fopen("example.txt", "r"); // 打开文件
if (file == NULL) {
printf("File opening failed.\n"); // 文件打开失败
return 1;
}
while ((ch = fgetc(file)) != EOF) { // 读取文件内容,直到文件结束
printf("%c", ch);
}
fclose(file); // 关闭文件
return 0;
}
```
5. 链表操作
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node *next;
};
void printList(struct Node *head) {
struct Node *current = head;
while (current != NULL) // 遍历链表
{
printf("%d ", current->data);
current = current->next;
}
}
int main() {
struct Node *head = NULL;
struct Node *second = NULL;
struct Node *third = NULL;
// 分配链表节点
head = (struct Node *) malloc(sizeof(struct Node));
second = (struct Node *) malloc(sizeof(struct Node));
third = (struct Node *) malloc(sizeof(struct Node));
head->data = 1;
head->next = second;
second->data = 2;
second->next = third;
third->data = 3;
third->next = NULL;
printList(head); // 打印链表
free(head); // 释放链表内存
free(second);
free(third);
return 0;
}
```
6. 指针操作
```c
#include <stdio.h>
int main() {
int num = 10;
int *ptr = # // 获取指针指向变量的地址
printf("Value: %d\n", *ptr); // 获取指针指向变量的值
printf("Address: %p\n", ptr); // 获取指针的值
printf("Address of variable: %p\n", &num); // 获取变量的地址
printf("Size of pointer: %lu bytes\n", sizeof(ptr)); // 获取指针的大小
return 0;
}
```
7. 位操作
```c
#include <stdio.h>
int main() {
unsigned int number = 10;
printf("Number: %u\n", number); // 打印原始数字
number = number | (1 << 2); // 通过位运算设置指定位
printf("Number after setting 2nd bit: %u\n", number);
number = number & ~(1 << 1); // 通过位运算清除指定位
printf("Number after clearing 1st bit: %u\n", number);
number = number ^ (1 << 0); // 通过位运算反转指定位
printf("Number after toggling 0th bit: %u\n", number);
return 0;
}
```