第10章《数组和指针》,回想当时刚接触C语言的时候觉得指针这块太晦涩难懂,确实是,很多人学习指针的时候都有这样的感觉。其实只要多做练习,就能渐渐熟悉指针到底是个神马东西,在程序中能起到什么样的作用。
开始本章习题:
2.编写一个程序,初始化一个double数组,然后把数组内容复制到另外两个数组(3个数组都需要在主程序中声明)。制作第一份拷贝的函数使用数组符号。制作第二份拷贝的函数使用指针符号,并使用指针的增量操作。把目标数组名和要复制的元素数目作为参数传递给函数。也就是说,如果给定了下列声明,函数调用应该如下面所示:
double source[5]={1.1,2.2,3.3,4.4,5.5};
double target1[5];
double target2[5];
copy_arr(source,target1,5);
copy_ptr(source,target1,5);
3.编写一个函数,返回一个int数组中存储的最大数值,并在一个简单的程序中测试这个函数。
4.编写一个函数,返回一个double数组中存储的最大值的索引,并在一个简单程序中测试这个函数。
5. 编写一个函数,返回一个double数组中存储的最大数值的索引,并在一个简单程序中测试这个函数。
开始本章习题:
1.修改程序清单10.7中的程序rain,使它不使用数组下标,而是使用指针进行计算(程序中仍然需要声明并初始化数组)。
//只要把ar[i]转换成*(ar+i)即可
2.编写一个程序,初始化一个double数组,然后把数组内容复制到另外两个数组(3个数组都需要在主程序中声明)。制作第一份拷贝的函数使用数组符号。制作第二份拷贝的函数使用指针符号,并使用指针的增量操作。把目标数组名和要复制的元素数目作为参数传递给函数。也就是说,如果给定了下列声明,函数调用应该如下面所示:
double source[5]={1.1,2.2,3.3,4.4,5.5};
double target1[5];
double target2[5];
copy_arr(source,target1,5);
copy_ptr(source,target1,5);
#include <stdio.h>
//使用数组符号完成拷贝
void copy_arr(double sou[],double tar[],int n);
//使用指针符号完成拷贝
void copy_ptr(double sou[],double tar[],int n);
//输出到屏幕上
void show(double sou[]);
int main(void)
{
double source[5]={1.1,2.2,3.3,4.4,5.5};
double target1[5];
double target2[5];
copy_arr(source,target1,5);
copy_ptr(source,target2,5);
printf("原始数组source: ");
show(source);
printf("拷贝后的数组target1:");
show(target1);
printf("拷贝后的数组target2: ");
show(target2);
return 0;
}
//使用数组符号完成拷贝
void copy_arr(double sou[],double tar[],int n)
{
int i;
for(i=0;i<5;i++)
tar[i]=sou[i];
}
//使用指针符号完成拷贝
void copy_ptr(double sou[],double tar[],int n)
{
int i;
for(i=0;i<5;i++)
*(tar+i)=*(sou+i);
}
//输出到屏幕上
void show(double sou[])
{
int i;
for(i=0;i<5;i++)
printf("%4.1f",sou[i]);
printf("\n");
}
3.编写一个函数,返回一个int数组中存储的最大数值,并在一个简单的程序中测试这个函数。
#include <stdio.h>
//找出数组中的最大值
int fmax(int ar[],int n);
int main(void)
{
int source[8]={2,3,6,34,4,12,35,65};
printf("最大值是%d\n",fmax(source,8));
return 0;
}
int fmax(int ar[],int n)
{
int i;
int max=ar[0];//初始化最大值
for(i=1;i<n;i++)
{
if(max<ar[i])//如果后来的数比max大就替换掉
max=ar[i];
}
return max;
}
4.编写一个函数,返回一个double数组中存储的最大值的索引,并在一个简单程序中测试这个函数。
#include <stdio.h>
double max;
int maxindex;//定义两个全局变量一个最大值,一个是最大值索引
//找出数组最大值的索引
void findex(double ar[],int n)
{
int i;
max=ar[0];
for(i=1;i<8;i++)
if(max<ar[i])
{
max=ar[i];
maxindex=i;
}
}
int main(void)
{
double soure[8]={1.1,23.3,42.3,34.4,55.2,67.5,33.2,36};
findex(soure,8);
printf("最大%.1f的索引号是%d\n",max,maxindex);
return 0;
}
5. 编写一个函数,返回一个double数组中存储的最大数值的索引,并在一个简单程序中测试这个函数。
#include <stdio.h>
//返回数组最大值与最小值之间的差值。
double diff(double ar[],int n)
{
double temp;
int i;
int j;
for(j=0;j<n-1;j++)//从大到小排列,双重循环(下沉法)
{
for (i=0;i<n-1;i++)
{
if (ar[i]<ar[i+1])//如果前一个数小于后一个数,两者互换
{
temp=ar[i+1];
ar[i+1]=ar[i];
ar[i]=temp;
}
}
}
return (ar[0]-ar[n-1]);//最大值减去最小值
}
int main(void)
{
double cha;
double source[8]={12,24,64,2,34,77,88,55};
cha=diff(source,8);
printf("数组中最大值%.f减去最小值%.1f的差值是%.1f\n",source[0],source[7],cha);
return 0;
}