指针练习题及答案
1. 请编写一个程序,交换两个变量的值,并通过指针来实现。
```c
#include<stdio.h>
void swap(int *a, int *b){
int temp = *a;
*a = *b;
*b = temp;
}
int main(){
int num1 = 10, num2 = 20;
printf("交换前的值:num1=%d, num2=%d\n", num1, num2);
swap(&num1, &num2);
printf("交换后的值:num1=%d, num2=%d\n", num1, num2);
return 0;
}
```
2. 编写一个函数,统计字符串中某个字符出现的次数,并通过指针返回结果。
```c
#include<stdio.h>
int countChar(const char *str, char target){
int count = 0;
while(*str != '\0'){
if(*str == target)
count++;
str++;
}
return count;
}
int main(){
char str[] = "hello world";
char target = 'l';
int count = countChar(str, target);
printf("字符 %c 出现的次数为:%d\n", target, count);
return 0;
}
```
3. 编写一个函数,到整型数组中的最大值,并通过指针返回结果。
```c
#include<stdio.h>
int findMax(const int *arr, int size){
int max = *arr;
for(int i = 1; i < size; i++){
if(*(arr+i) > max)
max = *(arr+i);
sizeof 指针 }
return max;
}
int main(){
int arr[] = {10, 20, 30, 40, 50};
int size = sizeof(arr) / sizeof(arr[0]);
int max = findMax(arr, size);
printf("数组中的最大值为:%d\n", max);
return 0;
}
```
4. 编写一个函数,将字符串反转,并通过指针返回结果。
```c
#include<stdio.h>
#include<string.h>
void reverseString(char *str){
int len = strlen(str);
for(int i = 0; i < len / 2; i++){
char temp = *(str+i);
*(str+i) = *(str+len-i-1);
*(str+len-i-1) = temp;
}
}
int main(){
char str[] = "Hello World";
printf("反转前的字符串:%s\n", str);
reverseString(str);
printf("反转后的字符串:%s\n", str);
return 0;
}
```
5. 编写一个程序,将一个数组中的奇数和偶数分离,并分别使用指针返回结果。
```c
#include<stdio.h>
void separateOddEven(int *arr, int size, int **odd, int **even){
*odd = (int*)malloc(size * sizeof(int));
*even = (int*)malloc(size * sizeof(int));
int oddCount = 0;
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论