#include "stdio.h"
#include
#include "time.h"
int main(int argc,char *argv[]){
int m,n,i,j,**p,*q;
srand((unsigned)time(NULL));
m=rand()%10+1;
while(m*(n=rand()%10+1)&1);//保证m*n是偶数
q=(int *)malloc(sizeof(int)*m*n);
if(q==NULL || (p=(int **)malloc(sizeof(int *)*m))==NULL){
printf("Application memory failure...\n");
return 0;
}
for(i=0;ifor(i=0;i for(j=0;j printf("%2d",p[i][j]=rand()%5+1);
printf("\n");
}
free(q);
free(p);
return 0;
}
运行样例:
【任务1】:
编写并测试3*3矩阵转置函数,使用数组保存3*3矩阵。
实验要求
(1) 转置函数参数为二维数组;
(2) 在main函数中实现输入、输出
#include
using namespace std;
static int b[3][3];
void change(int (*a)[3])//转置函数
{
for(int m=0;m<3;m++)
{
for(int n=0;n<3;n++)
{
b[m][n]=a[n][m];
}
}
}
int main()
{
int a[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
cin>>a[i][j];//双重for循环向二维数字里面输入数据
}
}
change(a);
for(int m=0;m<3;m++)
{
for(int n=0;n<3;n++)
{
cout<}
cout<
return 0;
}
【任务2】
使用new动态分配内存生成数组来实现任务一中的函数功能。
实验要求
(1) 转置函数参数为整形指针;
(2) 在main中使用new操作符分配内存生成动态数组,实现数组的输入和输出,函数结束时使用delete回收动态分配的内存空间。
(3) 通过Debug跟踪指针的值及其所指的对象的值。
#include
using namespace std;
static int b[3][3];//静态数组
void change(int (*a)[3])//转置函数
{
for(int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
b[i][j]=*(*(a+j)+i);//转置
}
}
}
int main()
{
int (*cp)[3]=new int[3][3];
for(int i=0;i<3;i++)
{
for (int j=0;j<3;j++)
{
cin>>*(*(cp+i)+j);//双重指针向二维数组里面输入数据
}
}
change(cp);
for(int m=0;m<3;m++)
{
for(int n=0;n<3;n++)
{
cout<}
cout<
return 0;
}
---------------------