在C语言中,数组和指针是两个非常重要的概念。它们不仅在日常编程中经常被使用,而且也是许多面试题和考试中的常见考点。通过一些针对性的练习,可以更好地掌握这两者的特性和应用。
练习一:数组与指针的基本操作
编写一个程序,定义一个整型数组并使用指针来访问其元素。要求:
- 定义一个包含5个整数的数组。
- 使用指针变量来遍历并打印数组中的每个元素。
- 修改数组中的某些值,并通过指针重新验证修改后的结果。
```c
include
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int p = arr;
for(int i=0; i<5; i++) {
printf("Element %d: %d\n", i, (p + i));
}
// 修改数组中的元素
(p + 2) = 10;
(p + 4) = 20;
printf("\nAfter modification:\n");
for(int i=0; i<5; i++) {
printf("Element %d: %d\n", i, (p + i));
}
return 0;
}
```
练习二:指针指向数组元素
编写一个程序,实现以下功能:
- 定义一个字符数组,存储一段字符串。
- 使用指针指向数组中的某个特定字符。
- 输出从该字符开始到字符串末尾的所有字符。
```c
include
include
int main() {
char str[] = "Hello World";
char ptr = strchr(str, 'W');
if(ptr != NULL) {
printf("String from 'W' to end: %s\n", ptr);
} else {
printf("Character not found.\n");
}
return 0;
}
```
练习三:二维数组与多级指针
编写一个程序,定义一个二维数组,并通过多级指针访问其中的元素。要求:
- 定义一个3x3的二维数组。
- 使用多级指针来访问并修改数组中的每个元素。
- 打印修改后的二维数组。
```c
include
int main() {
int arr[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
int (ptr)[3];
ptr = arr;
// 修改数组中的元素
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
ptr[i][j] += 10;
}
}
// 打印修改后的数组
for(int i=0; i<3; i++) {
for(int j=0; j<3; j++) {
printf("%d ", ptr[i][j]);
}
printf("\n");
}
return 0;
}
```
通过这些练习题,我们可以加深对数组和指针的理解,并熟练掌握它们的使用方法。希望这些题目能够帮助你巩固知识,提升编程技能!