C语言第七次实验报告

C程序设计实验报告

姓名:林世龙  实验地点:学校 实验时间:2020.06.03

 实验项目

8.31.指针基础及指针运算

8.3.2.数据交换

8.3.3.字符串反转及字符串连接

8.3.4.数组元素奇偶排列

一、实验目的与要求

1、加强对学生对指针数据类型的理解,熟悉指针的定义、通过指针间接访问变量的方法。
2、加强对指针类型作为函数参数传递的理解。
3、加强对字符指针及将指针作为函数的返回类型的理解,并通过指针对字符串进行操作。
4、加强对使用指针对数组进行操作的理解,通常数组的名称即整个数组的起始存储地址。

二、实验内容

8.3.1.指针基础及指针运算

1.问题的简单描述:定义整型指针变量p,使之指向整型变量a;定义浮点型指针q,使之指向浮点变量b,同时定义另外一个整型变量c并赋初值3。使用指针p,q输入a,b表达值;通过指针p,q间接输出a,b的值;输出p,q的值及c的地址。

2、实验代码:

#include <stdio.h>
int main()
{
	int *p,a,c=3;
	float *q,b;
	p=&a;
	q=&b;
	printf("Please Input the Value of a,b: ");
	scanf("%d%f",p,q);
	printf("Result: \n");
	printf("%d,%f\n",a,b);
	printf("%d,%f\n",*p,*q);
	printf("The Address of a,b:%p,%p\n",&a,&b);
	printf("The Address of a,b:%p,%p\n",p,q);
	p=&c;
	printf("c=%d\n ",*p);
	printf("The Address of c:%x,%x\n",p,&c);
	return 0;
}

 3、问题分析:无

8.3.2.数据交换

1问题的简单描述:从主函数中调用swap1和swap2函数,并打印输出交换后a、b的结果。
2实验代码:

#include<stdio.h>
void swap1(int x,int y);
void swap2(int *x,int *y);
int main()
{
	int a,b;
	printf("Please Input a=:");
	scanf("%d",&a);
	printf("\nb=:");
	scanf("%d",&b);
	swap1(a,b);
	printf("\nAfter Call swap1:a=%d,b=%d\n",a,b);
	swap2(&a,&b);  //指针作为形参,实参须为地址 
	printf("\nAfter Call swap2:a=%d,b=%d\n",a,b);
	return 0;
}
void swap1(int x,int y)
{
	int temp;
	temp=x;
	x=y;
	y=temp;
}
void swap2(int*x,int *y)
{
	int temp;
	temp=*x;
	*x=*y;
	*y=temp;
}

 3问题分析:当指针作为形式参数时,实际参数为地址

8.3.3.字符串反转及字符串连接

1问题的简单描述:定义两个字符指针,通过指针移动方式将字符串反转以及将两个字符串连接起来。
2实验代码:

#include <stdio.h>
char *reverse(char *str);
char *link(char *str1,char *str2);
int main()
{
	char str[30],str1[30],*str2;
	printf("Input Reversing Character String:");
	gets(str);
	str2=reverse(str);
	printf("\nOutput Reversed Characyer String:");
	puts(str2);
	printf("Input string1:");
	gets(str);
	printf("\nInput string2:");
	gets(str1);
	str2=link(str,str1);
	puts(str2);
	return 0;
 } 
 char *reverse(char *str)
 {
 	char *p,*q,temp;
 	p=str,q=str;
 	while(*p!='\0')
 	p++;
 	p--;
 	while(q<p)
 	{
 		temp=*q;
 		*q=*p;
 		*p=temp;
 		p--;
 		q++;
	 }
	 return str;
 }
 char *link(char *str1,char *str2)
 {
 	char *p=str1,*q=str2;
 	while(*p!='\0')
 	p++;
 	while(*q!='\0')
 	{
 		*p=*q;
 		p++;
 		q++;
	 }
	 *p='\0';
	 return str1;
 }

 3问题分析:刚开始对指针移动内容不太明白,后来经过老师讲解之后明白了

8.3.4.数组元素奇偶排列

1.问题的简单描述:定义一个函数,实现数组元素奇数在左、偶数在右。
2实验代码:

#include <stdio.h>
#define N 10
void arrsort(int a[],int n);
int main()
{
	int a[N],i;
	for(i=0;i<N;i++)
	scanf("%d",&a[i]);
	arrsort(a,N);
	for(i=0;i<N;i++)
	printf("%d ",a[i]);
 }
 void arrsort(int a[],int n)
 {
 	int *p,*q,temp;
 	p=a;
 	q=a+n-1;
 	while(p<q)
 	{
 		while(*p%2!=0)
 		p++;
 		while(*q%2==0)
 		q--;
 		if(p>q)
 		break;
 		temp=*p;
 		*p=*q;
 		*q=temp;
 		p++;
 		q--;
    }
  } 

 3问题分析:无

三、实验小结

指针这个单元学习的有点困难,没有书的模板根本做不出来,还有很多知识点需要自己多花时间消化学习。

 

posted @ 2020-06-08 09:32  1228687135  阅读(224)  评论(0)    收藏  举报