【真题1】2022年选择题第7题
设`int a[5] = {1,2,3,4,5}; int p = (int )(&a + 1);`,则`(p - 1)`的值是______。
解析:
- `&a`是数组指针,类型为`int ()[5]`,`&a + 1`跳过整个数组(偏移`5×sizeof(int)`字节)。
- `p = (int )(&a + 1)`将地址转为`int `,`p`指向`a[4]`之后的位置。
- `p - 1`指向`a[4]`,`(p - 1) = a[4] = 5`。
易错点:误认为`&a + 1`等价于`a + 5`(实际`a + 5`是`int `类型,指向`a[5]`(越界))。
【真题2】2021年编程题第1题
实现函数`void reverse(int arr, int n)`,将数组`arr`的前`n`个元素逆序。
#include <stdio.h>
void reverse(int arr, int n) {
if (arr == NULL || n <= 0) return; // 错误检查
int start = 0, end = n - 1;
while (start < end) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
int main() {
int a[] = {1,2,3,4,5};
reverse(a, 5);
for (int i = 0; i < 5; i++) printf("%d ", a[i]); // 输出:5 4 3 2 1
return 0;
}
高分要点:添加空指针与长度检查;使用`start`/`end`双指针避免重复交换。
【真题3】2023年填空题第5题
定义`union { int i; struct { char a, b, c, d; } s; } u; u.i = 0x01020304;` 在小端系统中,`u.s.d = ?`。
解析:
- 小端系统:低字节存低地址 → `u.i`内存布局为`04 03 02 01`。
- `u.s`中`d`是第4个成员(高地址)→ 对应字节`01`。
- 答案:`u.s.d = 0x01`。
陷阱:混淆成员顺序与字节顺序;未考虑小端/大端差异。
【真题4】2020年编程题第2题(节选)
用结构体实现链表,支持插入与删除节点。
typedef struct Node {
int data;
struct Node next;
} Node;
Node insert(Node head, int pos, int val) {
Node newNode = (Node)malloc(sizeof(Node));
if (!newNode) return head; // 内存分配失败
newNode->data = val;
newNode->next = NULL;
if (pos == 0) { // 插入头部
newNode->next = head;
return newNode;
}
Node cur = head;
for (int i = 0; i < pos - 1 && cur; i++) {
cur = cur->next;
}
if (!cur) return head; // 位置非法
newNode->next = cur->next;
cur->next = newNode;
return head;
}
void freeList(Node head) {
Node cur = head;
while (cur) {
Node tmp = cur;
cur = cur->next;
free(tmp); // 逐个释放
}
}
规范性体现:`freeList`确保无内存泄漏;`insert`中位置非法时返回原`head`。
【真题5】2024年选择题第12题
执行`FILE fp = fopen("test.txt", "w"); fwrite("abc", 1, 3, fp); fclose(fp);` 后,`ftell(fp)`的值是______。
解析:
- `fclose(fp)`后,`fp`变为悬垂指针,`ftell(fp)`行为未定义(但标准实现中返回`-1`)。
- 若在`fclose`前调用`ftell(fp)`,返回值为3(文件指针位置)。
考点:悬垂指针的非法操作;文件操作后立即关闭的影响。
【真题6】2022年编程题补充题
读取文本文件,统计单词数(单词定义:连续字母序列),忽略标点与数字。
#include <stdio.h>
#include <ctype.h>
int countWords(FILE fp) {
if (!fp) return -1;
int count = 0;
int inWord = 0;
int ch;
while ((ch = fgetc(fp)) != EOF) {
if (isalpha(ch)) {
if (!inWord) {
count++;
inWord = 1;
}
} else {
inWord = 0;
}
}
return count;
}
int main() {
FILE fp = fopen("test.txt", "r");
if (!fp) { perror("fopen"); return 1; }
printf("Words: %dn", countWords(fp));
fclose(fp);
return 0;
}
关键技巧:用`isalpha()`判断字母;`inWord`状态机避免重复计数(如“hello”只计1次)。