1. C语言基础入门

1.1 变量和数据类型

C语言中最基础的概念是变量和数据类型。变量是存储数据的容器,而数据类型则定义了变量可以存储的数据类型。以下是一些常见的数据类型和示例:

int age = 25; // 整数
float salary = 5000.50; // 浮点数
char grade = 'A'; // 字符

1.2 运算符和表达式

运算符用于对变量进行操作,而表达式则是运算符和变量的组合。以下是一些常见的运算符:

  • 算术运算符:+, -, *, /, %
  • 关系运算符:==, !=, <, >, <=, >=
  • 逻辑运算符:&&, ||, !

1.3 控制结构

控制结构用于控制程序的流程。以下是一些常见的控制结构:

  • 条件语句:if, else if, else
  • 循环语句:for, while, do-while

2. C语言进阶应用

2.1 函数

函数是C语言中组织代码的基本单元。以下是一个简单的函数示例:

#include <stdio.h>

// 函数声明
int add(int a, int b);

int main() {
    int result = add(5, 3);
    printf("The result is: %d\n", result);
    return 0;
}

// 函数定义
int add(int a, int b) {
    return a + b;
}

2.2 数组

数组是存储多个相同类型数据的集合。以下是一个使用数组的示例:

#include <stdio.h>

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

2.3 指针

指针是存储变量地址的变量。以下是一个使用指针的示例:

#include <stdio.h>

int main() {
    int x = 10;
    int *ptr = &x; // ptr指向x的地址
    printf("The value of x is: %d\n", *ptr);
    return 0;
}

3. C语言实战案例

以下是一些C语言的实战案例,帮助你更好地理解和应用C语言编程:

3.1 文件操作

#include <stdio.h>

int main() {
    FILE *file = fopen("example.txt", "r");
    if (file == NULL) {
        printf("Error opening file.\n");
        return 1;
    }
    char ch;
    while ((ch = fgetc(file)) != EOF) {
        printf("%c", ch);
    }
    fclose(file);
    return 0;
}

3.2 链表操作

#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));
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}

void insertAtBeginning(Node **head, int data) {
    Node *newNode = createNode(data);
    newNode->next = *head;
    *head = newNode;
}

void printList(Node *head) {
    while (head != NULL) {
        printf("%d ", head->data);
        head = head->next;
    }
    printf("\n");
}

int main() {
    Node *head = NULL;
    insertAtBeginning(&head, 3);
    insertAtBeginning(&head, 2);
    insertAtBeginning(&head, 1);
    printList(head);
    return 0;
}

3.3 字符串操作

#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("Concatenated string: %s\n", result);

    char *p = strstr(result, "World");
    printf("Found 'World' at index: %ld\n", p - result);

    return 0;
}

通过以上实战案例,你可以更好地掌握C语言编程。祝你学习愉快!