本文共 2430 字,大约阅读时间需要 8 分钟。
#include"stdafx.h"
//二维数组的操作
#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef int ElemType;
//定义数组结构体类型
typedef struct{
ElemType *base;
inth;
intl;
intelem_count;
ElemType *bounds;
}Array;
//输出数组
int Print_Array(Array &A){
int*p;
inti=1;
printf("当前的数组为:\n");
while(i<=A.h)
{
for(p=A.bounds;p<A.bounds+A.l;p++)
printf("%d ",*p);
printf("\n");
A.bounds=A.bounds+A.l;
i++;
}
A.bounds=A.base;
returnOK;
}
//建立数组
int InitArray(Array &A,intx,int y){
int*p;
inti=1;
A.h=x;
A.l=y;
A.elem_count=x*y;
A.base=(ElemType*)malloc(A.elem_count*sizeof(ElemType));
A.bounds=A.base;
while(i<=A.h)
{
printf("请输入第%d行元素:\n",i);
for(p=A.bounds;p<A.bounds+A.l;p++)
scanf("%d",p);
i++;
A.bounds=A.bounds+A.l;
}
A.bounds=A.base;
Print_Array(A);
returnOK;
}
//查找元素
int Seek_Elem(Array &A,intx,int y){
printf("要查找的元素的值为:\n%d",*(A.base+A.l*(x-1)+(y-1)));
returnOK;
}
//修改元素
int Revise_Elem(Array &A,intx,int y){
inta;
printf("请输入新数据:\n");
scanf("%d",&a);
*(A.base+A.l*(x-1)+(y-1))=a;
Print_Array(A);
returnOK;
}
//二维数组转置
int Transpose_Array(Array &A){
Array B;
int*p,*q;
inti=1;
B.base=A.base;
B.bounds=A.bounds;
B.h=A.h;
B.l=A.l;
B.elem_count=A.elem_count;
A.base=(ElemType*)malloc(A.elem_count*sizeof(ElemType));
A.bounds=A.base;
A.h=B.l;
A.l=B.h;
A.elem_count=A.h*A.l;
while(i<=A.h)
{
q=B.bounds;
for(p=A.bounds;p<A.bounds+A.l;p++)
{*p=*q;
q=q+B.l;}
B.bounds++;
A.bounds=A.bounds+A.l;
i++;
}
A.bounds=A.base;
Print_Array(A);
returnOK;
}
//销毁数组
int Destroy_Array(Array &A){
free(A.base);A.bounds=A.base=NULL;
A.h=A.l=A.elem_count=0;
printf("二维数组已销毁,请中止对它的操作!\n");
returnOK;
}
//主函数
void main()
{
Array A;
intx,y;
printf("请输入数组的行数:\n");
scanf("%d",&x);
printf("请输入数组的列数:\n");
scanf("%d",&y);
InitArray(A,x,y);
intflag=1,select;
printf("====================菜单============================\n");
printf("= 1.查找元素 =\n");
printf("= 2.修改元素 =\n");
printf("= 3.二维数组转置 =\n");
printf("= 4.销毁数组 =\n");
printf("= 5.退出操作 =\n");
printf("================支持乱序选择========================\n");
while(flag)
{
printf("\n请选择菜单中的操作选项:\n");
scanf("%d",&select);
switch(select)
{
case1:
printf("请输入要查找的元素所在行:\n");
scanf("%d",&x);
printf("请输入要查找的元素所在列:\n");
scanf("%d",&y);
Seek_Elem(A,x,y);break;
case2:
printf("请输入要修改的元素所在行:\n");
scanf("%d",&x);
printf("请输入要修改的元素所在列:\n");
scanf("%d",&y);
Revise_Elem(A,x,y);break;
case3:
Transpose_Array(A);break;
case4:
Destroy_Array(A);break;
case5:
flag=0;break;
default:
printf("您输入的数据有误!\n");
}
}
}
转载地址:http://zsdaf.baihongyu.com/