- 利用指针变量将一个数组中的数据反向输出。
#include <stdio.h>
void rev(int *arr, int size)
{
int *end = arr + size - 1;
for (int *ptr = end; ptr >= arr; ptr--)
{
printf("%-3d", *ptr);
}
printf("\n");
}
void get(int arr[], int len)
{
for (int i = 0; i < len; i++)
{
printf("%-3d", arr[i]);
}
printf("\n");
}
int main(int argc, char *argv[])
{
int arr[] = {1, 2, 3, 4, 5};
int size = sizeof(arr) / sizeof(arr[0]);
printf("原始数组:\n");
get(arr, size);
printf("反向输出的数组:\n");
rev(arr, size);
return 0;
}
2. 利用指针变量计算下标为奇数的数组的和;
#include <stdio.h>
int sunodd(int *arr, int size)
{
int sum = 0;
for (int i = 1; i < size; i += 2)
{
sum += *(arr + i);
}
return sum;
}
int main(int argc, char *argv[])
{
int arr[] = {1, 2, 3, 4, 5, 6, 7};
int size = sizeof(arr) / sizeof(arr[0]);
int sum = sunodd(arr, size);
printf("奇数下标对应数组索引和为%d\n", sum);
return 0;
}
3. 确认整型,字符型,浮点型指针变量的大小;
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Size of int pointer: %zu bytes\n", sizeof(int *));
printf("Size of char pointer: %zu bytes\n", sizeof(char *));
printf("Size of float pointer: %zu bytes\n", sizeof(float *));
printf("Size of double pointer: %zu bytes\n", sizeof(double *));
return 0;
return 0;
}
4. 利用指针变量输出字符数组中的所有字符。
#include <stdio.h>
int main(int argc, char *argv[])
{
char str[] = "Hello World";
char *ptr = str;
while (*ptr != '\0')
{
printf("%c", *ptr);
ptr++;
}
printf("\n");
return 0;
}
5. 编写一个函数,用指针变量做参数,用于求出一个浮点型数组元素的平均值。
#include <stdio.h>
double ave(float *arr, int size)
{
double sum = 0.0;
for (int i = 0; i < size; i++)
{
sum += *(arr + i);
}
return sum / size;
}
int main(int argc, char *argv[])
{
float numbers[] = {1.0, 2.5, 3.3, 4.8, 5.2};
int size = sizeof(numbers) / sizeof(numbers[0]);
double average = ave(numbers, size);
printf("平均值为:%.2f\n", average);
return 0;
}