C程序实验报告
实验项目:
1、指针基础及指针运算
2、数据交换
3、字符串反转及字符串连接
4、数组元素奇偶排列
姓名:王治林 实验地点:教学楼514教室 实验时间:2019.6.12
一、实验目的与要求
1、掌握指针的概念和定义方法
2、掌握指针的操作符和指针的运算
3、掌握指针与数组的关系
4、掌握指针与字符串的关系
5、熟悉指针作为函数的参数以及返回指针的函数
6、了解函数指针
二、实验内容
一、指针基础及指针运算(8.3.1)
1、问题的简单描述:
(1)定义一个整形指针变量p,使它指向一个整形变量a,定义一个浮点型指针q,使它指向一个浮点型变量b,同时定义另外一个整形变量c并赋初值3。
(2)使用指针变量,调用scanf函数分别输入a和b的值。
(3)通过指针间接访问并输出a、b的值。
(4)按十六进制方式输出p、q的值以及a、b的地址。
(5)将p指向c,通过p间接访问c的值并输出。
(6)输出p的值及c的地址,并与上面的结果进行比较。
2、实验代码:
#include<stdio.h> 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: "); printf("%d,%f ",a,b); printf("%d,%f ",*p,*q); printf("The Address of a,b:%p,%p ",&a,&b); printf("The Address of a,b:%p,%p ",p,q); p=&c; printf("c=%d ",*p); printf("The Address of a,b:%x,%x ",p,&c); return 0; }
3.运行效果:
4.问题分析:指针基本交换,比较简单
二、数据交换(8.3.2)
1、问题的简单描述:
(1)定义两个函数,分别为void swap1(int a,int b)和void swap2(int a,int b),用于交换a,b的值。
(2)从主函数中分别输入两个整形变量a、b。
(3)从主函数中分别调用上述两个交换函数,并打印输出交换后a、b的结果。
2、实验代码:
#include <stdio.h> void swap1 (int x,int y); void swap2 (int *x, int *y); main () { int a,b; printf("please input a= "); scanf("%d",&a); printf(" b=:"); scanf("%d",&b); swap1(a,b); printf("After call swap1 a=%d b=%d ",a,b); swap2(&a,&b); printf("After call swap2 a=%d b=%d ",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.实验效果:
4.实验分析:
注意指针和值的概念,转换起来才会知道步骤。还有注意当地址变化,值的变化与否。
三、字符串反转及字符串连接
1、问题的简单描述:
(1)定义两个字符指针,通过gets()函数输入两个字符串。
(2)定义一个函数char reverse(char str),通过指针移动方式将字符串反转。
(3)A定义一个函数char link(char str1,char *str2),通过指针移动方式将两个字符串连接起来。
(4)从主函数中分别调用上述函数,输入字符串并打印输出结果。
2、实验代码:
#include <stdio.h> char *reverse (char *str); char *link (char *str1,char *str2); main () { char str[30],str1[30],*str2; printf("input revesing character string:"); gets(str); str2=reverse(str); printf(" output revesed character string:"); puts(str2); printf("input string1: "); gets(str); printf(" input string2: "); gets(str1); str2=link(str, str1); printf("link string1 and string2 :"); puts(str2); return 0; } char*reverse(char *str) { char *p,*q,temp; p=str; q=str; while(*p!='