引言
C语言作为一种广泛使用的编程语言,在计算机科学和软件工程领域具有举足轻重的地位。张玉生作为一位著名的计算机科学专家,他的经典例题一直是学习和研究C语言的宝贵资源。本文将深入解析张玉生的经典C语言例题,并通过代码实战帮助读者更好地理解和掌握这些难题。
例题一:结构体与指针的深入应用
问题描述
编写一个C程序,定义一个结构体Student,包含学号、姓名和成绩。编写函数,输入一个学生的结构体指针,输出该学生的姓名和成绩。
解析
本例题考察了结构体、指针以及函数参数传递的知识点。
代码实现
#include <stdio.h>
typedef struct {
int id;
char name[50];
float score;
} Student;
void printStudentInfo(Student *stu) {
printf("Name: %s, Score: %.2f\n", stu->name, stu->score);
}
int main() {
Student stu = {1, "Alice", 90.5};
printStudentInfo(&stu);
return 0;
}
例题二:动态内存分配与释放
问题描述
编写一个C程序,使用动态内存分配创建一个整数数组,初始化数组元素,并输出数组元素。
解析
本例题考察了动态内存分配、初始化和释放的知识点。
代码实现
#include <stdio.h>
#include <stdlib.h>
int main() {
int *array;
int n = 5;
array = (int *)malloc(n * sizeof(int));
if (array == NULL) {
printf("Memory allocation failed\n");
return 1;
}
for (int i = 0; i < n; i++) {
array[i] = i * 2;
}
for (int i = 0; i < n; i++) {
printf("%d ", array[i]);
}
free(array);
return 0;
}
例题三:文件操作与字符串处理
问题描述
编写一个C程序,从文件中读取一行文本,使用字符串处理函数统计该行中单词的数量。
解析
本例题考察了文件操作、字符串处理和统计算法的知识点。
代码实现
#include <stdio.h>
#include <string.h>
int countWords(const char *line) {
int count = 0;
int inWord = 0;
while (*line) {
if (*line == ' ' || *line == '\n' || *line == '\t') {
inWord = 0;
} else if (!inWord) {
inWord = 1;
count++;
}
line++;
}
return count;
}
int main() {
FILE *file = fopen("input.txt", "r");
if (file == NULL) {
printf("File opening failed\n");
return 1;
}
char line[100];
while (fgets(line, sizeof(line), file)) {
printf("Number of words: %d\n", countWords(line));
}
fclose(file);
return 0;
}
总结
通过以上对张玉生经典C语言例题的解析和代码实战,读者可以更加深入地理解C语言的高级应用。这些例题不仅有助于提高编程技能,还能为解决实际问题提供宝贵的经验和思路。
