#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void ass_element(int *pta, int row, int col, int num);
int get_element(int * pta, int row, int col);
void print_array(int * pta, int row, int col);
void ass_element(int * pta, int row, int col, int num)
{
//待开发
}
int get_element(int * pta, int row, int col)
{
//待开发
}
void print_array(int * pta, int row, int col)
{
int i, j;
for (i = 0; i < row; i++)
{
for (j = 0; j < col; j++)
{
printf("%d ", pta[i*j + j]);
}
putchar('\n');
}
putchar('\n');
}
int main(void)
{
int command, row, col, temp_num;
int row_array, col_array;
int * pta = NULL;
char confirm, c;
printf("\n\
============================\n\
* 欢迎使用该程序,指令如下 *\n\
* 1.生成一个 M*N 的矩阵 *\n\
* 2.初始化矩阵 *\n\
* 3.给矩阵中某个元素赋值 *\n\
* 4.读取矩阵中某个元素 *\n\
* 5.打印整个矩阵 *\n\
* 6.结束程序 *\n\
============================\n");
while (1)
{
printf("\n请输入指令:");
scanf("%d", &command);
while (command < 1 || command > 6)
{
printf("指令输入错误,请重新输入:");
while ((c = getchar()) != EOF && c != '\n')
;
scanf("%d", &command);
}
if (command == 6)
break;
if (command == 1)
{
if (pta == NULL)
{
printf("请输入新矩阵的规模:");
while ((c = getchar()) != EOF && c != '\n')
;
scanf("%d*%d", &row, &col);
pta = (int *)malloc(row * col*sizeof(int));
memset(pta, 0, row*col*sizeof(int));
row_array = row;
col_array = col;
printf("%d*%d 的矩形创建成功!\n", row, col);
}
else
{
printf("矩阵已存在,是否需要重新创建?(Y/N)-> ");
while ((c = getchar()) != EOF && c != '\n')
;
scanf("%c", &confirm);
if (confirm == 'Y')
{
printf("请输入新矩阵的规模:");
while ((c = getchar()) != EOF && c != '\n')
;
scanf("%d*%d", &row, &col);
free(pta);
pta = (int *)malloc(row * col * sizeof(int));
row_array = row;
col_array = col;
memset(pta, 0, row_array * col_array * sizeof(int));
printf("%d*%d 的矩形创建成功!\n", row_array, col_array);
}
else
{
printf("创建失败。\n");
}
}
}
else if (command == 2)
{
if (pta == NULL) {
printf("矩形未创建!初始化失败。\n");
}else{
printf("请输入一个数字:");
while ((c = getchar()) != EOF && c != '\n')
;
scanf("%d", &temp_num);
memset(pta, temp_num, row_array * col_array * sizeof(int));
putchar('\n');
}
}
else if (command == 3)
{
if (pta == NULL) {
printf("矩形未创建!无法赋值。\n");
}else{
printf("请输入要修改的位置(行,列)-> ");
while ((c = getchar()) != EOF && c != '\n')
;
scanf("%d,%d", &row, &col);
printf("请输入一个数字:");
scanf("%d", &temp_num);
ass_element(pta, row, col, temp_num);
}
}
else if (command == 4)
{
if (pta == NULL) {
printf("矩阵未创建!无法读取元素。\n");
}else{
printf("请输入要读取的位置(行,列)-> ");
while ((c = getchar()) != EOF && c != '\n')
;
scanf("%d,%d", &row, &col);
printf("第%d行,第%d列的数字是:%d\n", row, col, get_element(pta, row, col));
}
}
else if (command == 5)
{
if (pta == NULL) {
printf("矩形未创建!无法打印。\n");
}else{
print_array(pta, row_array, col_array);
}
}
}
printf("\n感谢使用本程序^_^\n");
free(pta);
return 0;
}