实例1:C语言基本语法入门
在C语言的世界里,一切从基本的语法开始。让我们从printf和scanf开始,了解如何输出和接收用户输入。
#include <stdio.h>
int main() {
printf("Hello, World!\n");
int age;
printf("请输入你的年龄:");
scanf("%d", &age);
printf("你的年龄是:%d\n", age);
return 0;
}
实例2:变量和类型
变量是程序的基石,理解不同的数据类型对于编写有效的C代码至关重要。
int main() {
int num = 10;
float fnum = 10.5;
char letter = 'A';
printf("整数:%d\n", num);
printf("浮点数:%f\n", fnum);
printf("字符:%c\n", letter);
return 0;
}
实例3:运算符
C语言中的运算符非常丰富,从基本的算术运算到更复杂的位运算。
#include <stdio.h>
int main() {
int a = 5, b = 3;
printf("加法:%d\n", a + b);
printf("减法:%d\n", a - b);
printf("乘法:%d\n", a * b);
printf("除法:%d\n", a / b);
printf("余数:%d\n", a % b);
return 0;
}
实例4:控制流 - if语句
使用if语句,你可以根据条件执行不同的代码块。
#include <stdio.h>
int main() {
int age = 18;
if (age >= 18) {
printf("你可以投票了!\n");
} else {
printf("你还不能投票。\n");
}
return 0;
}
实例5:控制流 - while循环
while循环允许你重复执行代码,直到指定的条件不再满足。
#include <stdio.h>
int main() {
int i = 0;
while (i < 5) {
printf("循环中的数字:%d\n", i);
i++;
}
return 0;
}
实例6:控制流 - for循环
for循环是处理重复任务时的强大工具。
#include <stdio.h>
int main() {
for (int i = 0; i < 5; i++) {
printf("循环中的数字:%d\n", i);
}
return 0;
}
实例7:函数定义和调用
函数是组织代码的方式,使代码更易于管理和重用。
#include <stdio.h>
void greet() {
printf("你好,世界!\n");
}
int main() {
greet();
return 0;
}
实例8:数组操作
数组是存储一系列相同类型数据的方式。
#include <stdio.h>
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
printf("数组中的数字:%d\n", numbers[i]);
}
return 0;
}
实例9:指针和地址
指针是存储变量地址的数据类型,它们在内存管理中非常重要。
#include <stdio.h>
int main() {
int a = 10;
int *ptr = &a;
printf("a的值:%d\n", a);
printf("指针指向的值:%d\n", *ptr);
return 0;
}
实例10:结构体
结构体允许你将多个不同类型的数据组合成一个单一的实体。
#include <stdio.h>
typedef struct {
char name[50];
int age;
} Person;
int main() {
Person p = {"Alice", 30};
printf("姓名:%s\n", p.name);
printf("年龄:%d\n", p.age);
return 0;
}
实例11:函数参数传递
在C语言中,函数参数可以通过值传递和引用传递。
#include <stdio.h>
void changeValue(int value) {
value = 100;
}
void main() {
int x = 50;
changeValue(x);
printf("x的值:%d\n", x); // 输出50,因为参数是值传递
}
实例12:动态内存分配
使用malloc和free,你可以动态地在运行时分配和释放内存。
#include <stdio.h>
#include <stdlib.h>
int main() {
int *ptr = (int *)malloc(10 * sizeof(int));
if (ptr == NULL) {
printf("内存分配失败\n");
return 1;
}
for (int i = 0; i < 10; i++) {
ptr[i] = i;
}
free(ptr);
return 0;
}
实例13:字符串操作
C语言中处理字符串的方法相对简单,但功能强大。
#include <stdio.h>
#include <string.h>
int main() {
char str1[100] = "Hello";
char str2[100] = "World";
char result[200];
strcpy(result, str1);
strcat(result, str2);
printf("合并后的字符串:%s\n", result);
return 0;
}
实例14:文件操作
C语言允许你以只读或写入模式打开文件,并执行各种文件操作。
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "w");
if (file == NULL) {
printf("文件打开失败\n");
return 1;
}
fprintf(file, "这是写入的内容\n");
fclose(file);
file = fopen("example.txt", "r");
if (file == NULL) {
printf("文件打开失败\n");
return 1;
}
char buffer[100];
while (fgets(buffer, 100, file) != NULL) {
printf("%s", buffer);
}
fclose(file);
return 0;
}
实例15:结构体和函数
你可以将结构体作为函数的参数,并在函数中修改它们。
#include <stdio.h>
typedef struct {
int x;
int y;
} Point;
void movePoint(Point *p, int dx, int dy) {
p->x += dx;
p->y += dy;
}
int main() {
Point p = {1, 2};
movePoint(&p, 3, 4);
printf("移动后的点:%d, %d\n", p.x, p.y);
return 0;
}
实例16:指针和数组
指针可以用来访问数组的元素,这有助于理解内存如何工作。
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr;
for (int i = 0; i < 5; i++) {
printf("数组元素:%d\n", *(ptr + i));
}
return 0;
}
实例17:函数指针
函数指针可以指向函数,允许你以更灵活的方式使用函数。
#include <stdio.h>
void printMessage(const char *message) {
printf("消息:%s\n", message);
}
int main() {
void (*funcPtr)(const char *) = printMessage;
funcPtr("通过函数指针调用");
return 0;
}
实例18:递归函数
递归是一种强大的编程技术,允许函数调用自身。
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
int main() {
int num = 5;
printf("阶乘:%d\n", factorial(num));
return 0;
}
实例19:结构体数组和指针
你可以使用结构体数组和指针来处理更复杂的数据。
#include <stdio.h>
typedef struct {
char name[50];
int age;
} Person;
int main() {
Person people[3] = {
{"Alice", 30},
{"Bob", 25},
{"Charlie", 35}
};
Person *ptr = people;
for (int i = 0; i < 3; i++) {
printf("姓名:%s, 年龄:%d\n", ptr[i].name, ptr[i].age);
}
return 0;
}
实例20:联合体
联合体允许你在同一内存位置存储不同类型的数据。
#include <stdio.h>
typedef union {
int i;
float f;
char c[4];
} UnionType;
int main() {
UnionType ut;
ut.i = 10;
printf("整数值:%d\n", ut.i);
ut.f = 10.5;
printf("浮点数值:%f\n", ut.f);
memcpy(ut.c, "ABC", 3);
printf("字符数组:%s\n", ut.c);
return 0;
}
实例21:枚举类型
枚举类型用于定义一组命名的整型常量。
#include <stdio.h>
typedef enum {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
} Weekday;
int main() {
Weekday today = TUESDAY;
printf("今天是:%d\n", today);
return 0;
}
实例22:位字段
位字段允许你以更紧凑的方式存储数据。
#include <stdio.h>
typedef struct {
unsigned int hour : 5;
unsigned int minute : 6;
unsigned int second : 5;
} Time;
int main() {
Time t = {12, 34, 56};
printf("时间:%02d:%02d:%02d\n", t.hour, t.minute, t.second);
return 0;
}
实例23:输入输出重定向
在C语言中,你可以使用重定向操作符来改变标准输入和输出的方向。
#include <stdio.h>
int main() {
int x;
printf("请输入一个整数:");
scanf("%d", &x);
printf("你输入的整数是:%d\n", x);
return 0;
}
实例24:宏定义
宏定义允许你创建简短的代码片段,它们可以在整个程序中重复使用。
#include <stdio.h>
#define PI 3.14159
int main() {
printf("PI的值:%f\n", PI);
return 0;
}
实例25:预处理器指令
预处理器指令在编译前处理源代码,例如条件编译。
#include <stdio.h>
#if defined(__linux__)
#define OS "Linux"
#elif defined(__windows__)
#define OS "Windows"
#else
#define OS "Unknown"
#endif
int main() {
printf("操作系统:%s\n", OS);
return 0;
}
实例26:错误处理
错误处理是编写健壮程序的关键部分。
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
perror("文件打开失败");
return EXIT_FAILURE;
}
fclose(file);
return EXIT_SUCCESS;
}
实例27:动态链接库
动态链接库允许你将代码分割成模块,以便在不同程序之间共享。
// example.c
#include <stdio.h>
void printHello() {
printf("Hello, World!\n");
}
// example.h
#ifndef EXAMPLE_H
#define EXAMPLE_H
void printHello();
#endif // EXAMPLE_H
// main.c
#include <stdio.h>
#include "example.h"
int main() {
printHello();
return 0;
}
实例28:信号处理
信号处理允许你响应操作系统发送的特定事件。
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
void signalHandler(int signum) {
printf("捕获信号:%d\n", signum);
}
int main() {
signal(SIGINT, signalHandler);
while (1) {
printf("程序运行中...\n");
sleep(1);
}
return 0;
}
实例29:多线程
多线程允许你同时执行多个任务。
#include <stdio.h>
#include <pthread.h>
void *threadFunction(void *arg) {
printf("线程ID:%ld\n", pthread_self());
return NULL;
}
int main() {
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, threadFunction, NULL);
pthread_create(&thread2, NULL, threadFunction, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
实例30:进程间通信
进程间通信(IPC)允许不同进程之间交换数据。
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// 子进程
printf("子进程,PID:%d\n", getpid());
} else {
// 父进程
printf("父进程,PID:%d\n", getpid());
wait(NULL);
}
return 0;
}
实例31:网络编程
网络编程允许你的程序与其他计算机通信。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
int main() {
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
perror("套接字创建失败");
return 1;
}
struct sockaddr_in serveraddr;
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(80);
serveraddr.sin_addr.s_addr = inet_addr("www.google.com");
if (connect(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) == -1) {
perror("连接失败");
return 1;
}
char buffer[1024];
read(sockfd, buffer, sizeof(buffer));
printf("从服务器接收到的数据:%s\n", buffer);
close(sockfd);
return 0;
}
实例32:数据库操作
C语言可以与数据库进行交互,例如使用SQLite。
#include <stdio.h>
#include <sqlite3.h>
int main() {
sqlite3 *db;
char *errMsg = 0;
int rc = sqlite3_open("example.db", &db);
if (rc != SQLITE_OK) {
fprintf(stderr, "无法打开数据库:%s\n", sqlite3_errmsg(db));
return 1;
}
char *sql = "CREATE TABLE IF NOT EXISTS people (id INTEGER PRIMARY KEY, name TEXT, age INTEGER);";
rc = sqlite3_exec(db, sql, 0, 0, &errMsg);
if (rc != SQLITE_OK) {
fprintf(stderr, "SQL错误:%s\n", errMsg);
sqlite3_free(errMsg);
sqlite3_close(db);
return 1;
}
sqlite3_close(db);
return 0;
}
实例33:文件系统操作
C语言可以用来操作文件系统,例如创建、删除和列出文件。
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
int main() {
const char *filename = "example.txt";
struct stat st;
// 创建文件
FILE *file = fopen(filename, "w");
if (file == NULL) {
perror("文件创建失败");
return 1;
}
fclose(file);
// 检查文件是否存在
if (stat(filename, &st) == -1) {
perror("文件状态获取失败");
return 1;
} else {
printf("文件存在\n");
}
// 删除文件
if (remove(filename) != 0) {
perror("文件删除失败");
return 1;
}
return 0;
}
实例34:图形界面编程
C语言可以用于创建图形用户界面(GUI)应用程序。
#include <stdio.h>
#include <stdlib.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
int main() {
Display *display = XOpenDisplay(NULL);
if (display == NULL) {
fprintf(stderr, "无法打开显示\n");
return 1;
}
Window window = XCreateSimpleWindow(display, DefaultRootWindow(display), 100, 100, 200, 200, 1, BlackPixel(display, DefaultScreen(display)), WhitePixel(display, DefaultScreen(display)));
XMapWindow(display, window);
XEvent event;
XSelectInput(display, window, ExposureMask | KeyPressMask);
while (1) {
XNextEvent(display, &event);
switch (event.type) {
case Expose:
XDrawString(display, window, DefaultGC(display, DefaultScreen(display)), 100, 100, "Hello, World!", 13);
break;
case KeyPress:
XCloseDisplay(display);
return 0;
}
}
}
实例35:多线程同步
多线程同步是确保线程安全执行的关键。
”`c
#include
int counter = 0; pthread_mutex_t lock;
void *threadFunction(void *arg) {
for (int i = 0; i < 1000; i++) {
pthread_mutex_lock(&lock);
counter++;
pthread_mutex_unlock(&lock);
}
return NULL;
}
int main() {
pthread_t threads[10];
pthread_mutex_init(&lock, NULL);
for (int i = 0; i < 10; i++) {
pthread_create(&threads[i], NULL,
