实例1:理解C语言基础语法
在C语言编程中,基础语法是基石。以下是一个简单的“Hello, World!”程序示例:
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
这个例子中,#include <stdio.h> 是预处理指令,用于包含标准输入输出库。int main() 是程序的入口点。printf() 函数用于打印输出。
实例2:变量和数据类型
了解不同的数据类型和变量声明是编写C语言程序的关键。以下是一个示例:
int age = 25;
float salary = 5000.75;
char grade = 'A';
在这个例子中,我们声明了三个变量:一个整数age,一个浮点数salary,和一个字符grade。
实例3:运算符的使用
C语言中的运算符包括算术运算符、赋值运算符、关系运算符等。以下是一个算术运算符的示例:
int a = 10, b = 5;
int sum = a + b; // sum 的值为 15
在这个例子中,我们使用了加号+来计算两个整数的和。
实例4:控制结构
控制结构如if、else和switch用于根据条件执行不同的代码块。以下是一个if语句的示例:
int number = 10;
if (number > 0) {
printf("Number is positive.\n");
} else {
printf("Number is negative or zero.\n");
}
这个例子中,如果number大于0,程序将打印“Number is positive.”;否则,打印“Number is negative or zero.”。
实例5:循环结构
循环结构如for、while和do-while用于重复执行代码块。以下是一个for循环的示例:
for (int i = 0; i < 5; i++) {
printf("Loop iteration: %d\n", i);
}
在这个例子中,for循环会重复执行5次,每次打印当前的迭代次数。
实例6:函数的定义和使用
函数是C语言中的核心概念之一。以下是一个简单函数的示例:
#include <stdio.h>
void greet() {
printf("Hello, User!\n");
}
int main() {
greet();
return 0;
}
在这个例子中,greet函数用于打印一条消息。
实例7:指针和内存管理
指针是C语言中非常强大的特性,但同时也是容易出错的地方。以下是一个指针的示例:
int x = 5;
int *ptr = &x; // ptr 指向变量 x 的地址
printf("Value of x: %d\n", *ptr); // 输出 x 的值
在这个例子中,ptr是一个指向整数x的指针。
实例8:结构体和联合体
结构体和联合体是用于组织相关数据的自定义数据类型。以下是一个结构体的示例:
#include <stdio.h>
typedef struct {
char name[50];
int age;
float salary;
} Employee;
int main() {
Employee emp = {"John Doe", 30, 50000.0};
printf("Employee Name: %s\n", emp.name);
printf("Employee Age: %d\n", emp.age);
printf("Employee Salary: %.2f\n", emp.salary);
return 0;
}
在这个例子中,我们定义了一个名为Employee的结构体,并创建了一个Employee类型的变量emp。
实例9:动态内存分配
动态内存分配允许程序在运行时分配和释放内存。以下是一个使用malloc和free的示例:
#include <stdio.h>
#include <stdlib.h>
int main() {
int *numbers = (int*)malloc(5 * sizeof(int));
if (numbers == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
for (int i = 0; i < 5; i++) {
numbers[i] = i * 2;
}
for (int i = 0; i < 5; i++) {
printf("Number %d: %d\n", i, numbers[i]);
}
free(numbers); // 释放分配的内存
return 0;
}
在这个例子中,我们使用malloc函数动态分配了一个整数的数组,并在使用完毕后使用free函数释放了内存。
实例10:文件操作
文件操作是C语言中常用的功能,以下是一个读取和写入文件的示例:
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "w"); // 打开文件用于写入
if (file == NULL) {
printf("File opening failed.\n");
return 1;
}
fprintf(file, "This is a test.\n"); // 写入文件
fclose(file); // 关闭文件
file = fopen("example.txt", "r"); // 打开文件用于读取
if (file == NULL) {
printf("File opening failed.\n");
return 1;
}
char buffer[100];
while (fgets(buffer, sizeof(buffer), file)) {
printf("%s", buffer); // 读取并打印文件内容
}
fclose(file); // 关闭文件
return 0;
}
在这个例子中,我们首先打开一个文件用于写入,写入一些文本,然后关闭文件。接着,我们再次打开同一个文件用于读取,并打印文件内容。
实例11:字符串处理
C语言中的字符串处理是编程中常见的任务。以下是一个字符串处理的示例:
#include <stdio.h>
#include <string.h>
int main() {
char str1[100] = "Hello";
char str2[] = "World";
char result[100];
strcpy(result, str1); // 复制字符串
strcat(result, str2); // 连接字符串
printf("Concatenated String: %s\n", result); // 输出结果
printf("Length of str1: %lu\n", strlen(str1)); // 获取字符串长度
printf("Index of 'o' in str1: %d\n", strchr(str1, 'o') - str1); // 查找字符位置
return 0;
}
在这个例子中,我们使用strcpy和strcat函数来复制和连接字符串,使用strlen函数获取字符串长度,以及使用strchr函数查找字符的位置。
实例12:使用库函数
C语言标准库提供了许多实用的函数,以下是一个使用time和strftime函数的示例:
#include <stdio.h>
#include <time.h>
int main() {
time_t rawtime;
struct tm *timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
char buffer[80];
strftime(buffer, sizeof(buffer), "%A, %d %B %Y %H:%M:%S", timeinfo);
printf("Current time: %s\n", buffer);
return 0;
}
在这个例子中,我们使用time函数获取当前时间,使用localtime函数将时间转换为本地时间,然后使用strftime函数格式化时间。
实例13:错误处理
错误处理是编程中不可或缺的一部分。以下是一个简单的错误处理示例:
#include <stdio.h>
#include <stdlib.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; // 错误处理
}
printf("Result: %d\n", result);
return 0;
}
在这个例子中,如果尝试除以零,函数divide将打印错误信息并返回-1。在main函数中,我们检查函数返回值,以确定是否发生了错误。
实例14:动态字符串分配
动态字符串分配是C语言中的一个高级特性。以下是一个动态分配和释放字符串的示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *str = (char*)malloc(100 * sizeof(char));
if (str == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
strcpy(str, "Hello, World!");
printf("String: %s\n", str);
free(str); // 释放分配的内存
return 0;
}
在这个例子中,我们使用malloc动态分配了一个字符串,使用strcpy复制了字符串,并在使用完毕后使用free释放了内存。
实例15:递归函数
递归是C语言中的一个有趣概念,以下是一个使用递归计算阶乘的示例:
#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;
}
在这个例子中,factorial函数递归地计算阶乘。
实例16:指针和数组
指针和数组是C语言中紧密相关的概念。以下是一个使用指针和数组的示例:
#include <stdio.h>
int main() {
int numbers[5] = {1, 2, 3, 4, 5};
int *ptr = numbers;
for (int i = 0; i < 5; i++) {
printf("Value at index %d: %d\n", i, *(ptr + i));
}
return 0;
}
在这个例子中,我们使用指针访问数组元素。
实例17:函数指针
函数指针是C语言中的另一个高级特性,以下是一个使用函数指针的示例:
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main() {
int (*func)(int, int) = add;
printf("Sum: %d\n", func(3, 4));
return 0;
}
在这个例子中,我们定义了一个名为add的函数,并将其地址赋给一个函数指针func。
实例18:结构体数组
结构体数组是C语言中用于组织相关数据的常用方式。以下是一个结构体数组的示例:
#include <stdio.h>
typedef struct {
char name[50];
int age;
float salary;
} Employee;
int main() {
Employee employees[3] = {
{"John Doe", 30, 50000.0},
{"Jane Smith", 25, 60000.0},
{"Bob Johnson", 35, 55000.0}
};
for (int i = 0; i < 3; i++) {
printf("Employee %d: %s, %d, %.2f\n", i + 1, employees[i].name, employees[i].age, employees[i].salary);
}
return 0;
}
在这个例子中,我们定义了一个名为Employee的结构体,并创建了一个包含三个Employee类型的数组。
实例19:指针数组
指针数组是C语言中用于存储指针的数组。以下是一个指针数组的示例:
#include <stdio.h>
int main() {
int a = 10, b = 20, c = 30;
int *ptrs[3] = {&a, &b, &c};
for (int i = 0; i < 3; i++) {
printf("Value at index %d: %d\n", i, *ptrs[i]);
}
return 0;
}
在这个例子中,我们定义了一个包含三个整数的指针数组ptrs,并使用指针访问数组元素。
实例20:字符串数组
字符串数组是C语言中用于存储字符串的数组。以下是一个字符串数组的示例:
#include <stdio.h>
int main() {
char *strings[3] = {"Hello", "World", "C Programming"};
for (int i = 0; i < 3; i++) {
printf("%s\n", strings[i]);
}
return 0;
}
在这个例子中,我们定义了一个包含三个字符串的指针数组strings,并使用指针访问数组元素。
实例21:二维数组
二维数组是C语言中用于存储表格数据的常用方式。以下是一个二维数组的示例:
#include <stdio.h>
int main() {
int numbers[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("numbers[%d][%d] = %d\n", i, j, numbers[i][j]);
}
}
return 0;
}
在这个例子中,我们定义了一个名为numbers的二维数组,并使用嵌套循环访问数组元素。
实例22:动态二维数组
动态二维数组是C语言中用于动态分配和释放二维数据的常用方式。以下是一个动态二维数组的示例:
#include <stdio.h>
#include <stdlib.h>
int main() {
int rows = 3, cols = 4;
int **numbers = (int**)malloc(rows * sizeof(int*));
for (int i = 0; i < rows; i++) {
numbers[i] = (int*)malloc(cols * sizeof(int));
for (int j = 0; j < cols; j++) {
numbers[i][j] = i * cols + j;
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("numbers[%d][%d] = %d\n", i, j, numbers[i][j]);
}
}
for (int i = 0; i < rows; i++) {
free(numbers[i]);
}
free(numbers);
return 0;
}
在这个例子中,我们使用malloc动态分配了一个二维数组,并使用嵌套循环访问数组元素。
实例23:结构体指针
结构体指针是C语言中用于指向结构体的指针。以下是一个结构体指针的示例:
#include <stdio.h>
typedef struct {
char name[50];
int age;
} Person;
int main() {
Person person = {"John Doe", 30};
Person *ptr = &person;
printf("Name: %s, Age: %d\n", ptr->name, ptr->age);
return 0;
}
在这个例子中,我们定义了一个名为Person的结构体,并创建了一个指向该结构体的指针ptr。
实例24:链表
链表是C语言中用于动态数据结构的一种常见方式。以下是一个单向链表的示例:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node* createNode(int data) {
Node *newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
return NULL;
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void insertNode(Node **head, int data) {
Node *newNode = createNode(data);
if (newNode == NULL) {
return;
}
if (*head == NULL) {
*head = newNode;
return;
}
Node *current = *head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
void printList(Node *head) {
Node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
void freeList(Node *head) {
Node *current = head;
while (current != NULL) {
Node *temp = current;
current = current->next;
free(temp);
}
}
int main() {
Node *head = NULL;
insertNode(&head, 1);
insertNode(&head, 2);
insertNode(&head, 3);
printList(head);
freeList(head);
return 0;
}
在这个例子中,我们定义了一个名为Node的结构体,并创建了一个单向链表。我们使用createNode函数创建节点,使用insertNode函数插入节点,使用printList函数打印链表,以及使用freeList函数释放链表。
实例25:队列
队列是一种先进先出(FIFO)的数据结构。以下是一个使用链表实现的队列的示例:
”`c
#include
typedef struct Node {
int data;
struct Node *next;
} Node;
typedef struct Queue {
Node *front;
Node *rear;
} Queue;
Queue* createQueue() {
Queue *queue = (Queue*)malloc(sizeof(Queue));
if (queue == NULL) {
printf("Memory allocation failed.\n");
return NULL;
}
queue->front = NULL;
queue->rear = NULL;
return queue;
}
void enqueue(Queue *queue, int data) {
Node *newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Memory allocation failed.\n");
return;
}
newNode->data = data;
newNode->next = NULL;
if (queue->rear == NULL) {
queue->front = newNode;
queue->rear = newNode;
return;
}
queue->rear->next = newNode;
queue->rear = newNode;
