我一直在尝试这个代码,它不能很好地工作。从输入动态分配矩阵 - C
void *matrix_allocate_variable (int size)
{
void *p1;
if ((p1=(int*)malloc(size))==NULL){
printf("out of memory.\n");
exit(1);
}
return p1;
}
在这里,我创建了一个调用的malloc
和退出时的错误,这样我就可以在我的下一个函数使用它的功能:
void matrix_new(int **matrices, int *row_counts, int *column_counts, char specifier)
{
int index, i;
index= (int)(specifier-'A');
scanf("%d",&row_counts[index]);
scanf("%d",&column_counts[index]);
matrices[index]= (int*)matrix__allocate_variable(sizeof(int)* (row_counts[index]*column_counts[index]);
这里就是我有问题。我试图让用户输入一些用于创建矩阵的输入,但是我有很多问题试图使其工作。有人能帮我开始吗?
PS。有关更多详细信息,我将在functions.c
中创建函数,这是迄今为止我所拥有的功能。我有一个main.c
,它调用了这些函数,以便稍后我可以添加,删除和转置,但是现在我试图输入数据,这是我遇到的很多麻烦。这里是我的main.c
,我称之为功能。
/* Pointer to the set of matrix registers. */
int **matrices = NULL;
/* row_counts[i] stores the number of rows in matrix i */
int *row_counts = NULL;
/* column_counts[i] stores the number of columns in matrix i */
int *column_counts = NULL;
/**********************************************************************
Skeleton code part B: suggested form for selected variable initializations
**********************************************************************/
/* Initialize the matrix set. */
matrices = (int**) matrix_allocate_variable(...);
column_counts = (int *)matrix_allocate_variable(...);
row_counts = (int *)matrix_allocate_variable(...);
char call[2];
int error = 2;
do {
printf ("> ");
if (scanf ("%1s", call) !=1) {
fprintf (stderr, "Command not found. \n");
exit (1);
}
switch (call [0]) {
case 'A': matrix_new(matrices,row_counts,column_counts,'A');
break;
case 'B': matrix_new(matrices,row_counts,column_counts,'B');
break;
case 'C': matrix_new(matrices,row_counts,column_counts,'C');
break;
case 'D': matrix_new(matrices,row_counts,column_counts,'D');
break;
case '+': matrix_add(matrices,row_counts,column_counts);
break;
case '^': matrix_tranpose(matrices,row_counts,column_counts);
break;
case '*': matrix_multiply(matrices,row_counts,column_counts);
break;
case '$': exit (1);
default : fprintf (stderr, "Command not found. \n");
}
} while (error != 1);
return 0;
}
任何帮助都会很好,我接下来要做的任何指示都很棒。非常感谢你的每一个。
http://stackoverflow.com/questions/16004668/c-allocating-a-matrix-in-a-function/27366086#27366086 上面你会发现,我已经与由程序函数以任何可能的方式为C(gcc C11/C99)分配和操作矩阵。 – 42n4