My question is regrading the second function
float *rowavg(float *matrix,int rows,int cols)
So i'm suppose to dynamically allocate an array of floats with row elements and return NULL if allocation fails. I think i did this right, right? The other part that i'm trying to do is set the ith element of the new array to the average of the values in the ith row of the previous array. This part is where I'm getting got up. Did i call the previous array correctly(I believe no)?
#include <stdio.h>
#include <stdlib.h>
float *readMatrix(int rows, int cols);
float *rowavg(float *matrix, int rows, int cols);
float *colavg(float *matrix, int rows, int cols);
#define MAX_DIM 10
int main(void)
{
int done = 0;
int rows, cols;
float *dataMatrix;
float *rowAveVector;
float *colAveVector;
float overallAve;
while (!done)
{
do
{
printf("Enter row dimension (must be between 1 and %d): ", MAX_DIM);
scanf("%d", &rows);
} while(rows <= 0 || rows > MAX_DIM);
do
{
printf("Enter column dimension (must be between 1 and %d): ", MAX_DIM);
scanf("%d", &cols);
} while(cols <= 0 || cols > MAX_DIM);
dataMatrix = readMatrix(rows, cols);
if (dataMatrix == NULL)
{
printf ("Program terminated due to dynamic memory allocation failure\n");
return (0);
}
rowAveVector = rowAverage(dataMatrix, rows, cols);
colAveVector = colAverage(dataMatrix, rows, cols);
if(rowAveVector == NULL || colAveVector == NULL)
{
printf("malloc failed. Terminating program\n");
return (0);
}
}
float *readMatrix(int rows, int cols)
//Dynamically allocate an array to hold a matrix of floats.
//The dimension of the matrix is numRows x numCols.
//If the malloc fails, return NULL.
//Otherwise, prompt the user to enter numRows*numCols values
//for the matrix in by-row order.
//Store the values entered by the user into the array and
//return a pointer to the array.
{
int i=0;
int j=0;
int elements=0;
float *m=malloc(rows*cols*sizeof(float));
if (m==NULL)
{
printf("error\n");
return NULL;
}
printf("Enter values for the matrix: ");
for (i=0;i<rows;i++)
{
for (j=0;j<cols;j++)
{
elements = i*cols+j;
scanf("%f", &m[elements]);
}
}
return m;
}
float *rowavg(float *matrix, int rows, int cols)
{
int i=0;
float mean=0;
float *mat=malloc(rows*sizeof(float));
if(mat==NULL)
{
printf("error\n");
return NULL;
}
for (i=0;i<rows;i++)
{
readMatrix(rows,cols);
mean=
mat[i]=mean;
}
}
First of all, call of readMatrix(rows,cols); not needed in rowavg.
And if you want rowavg to return average values for each row in your matrix, try the following:
float *rowavg(float *matrix, int rows, int cols)
{
// check matrix befor use
if (matrix == NULL)
{
return NULL;
}
int i=0;
int j=0;
double mean; // variable name from original code in the question
float *avgarr = (float *)malloc(rows*sizeof(float));
if(avgarr == NULL)
{
return NULL;
}
for (i=0;i<rows;i++)
{
mean = 0.0;
for (j=0;j<cols;j++)
{
mean += matrix[i*cols+j];
}
avgarr[i] = (float)(mean/cols);
}
return avgarr;
}
And because in main you already have
rowAveVector = rowAverage(dataMatrix, rows, cols);
if(rowAveVector == NULL)
{
printf("malloc failed. Terminating program\n");
return (0); // here consider return value different from 0
}
you should not use printf("error\n"); in rowavg.
And think over using free after allocatied memory not needed any more.
Related
Write a C program to convert 1D array to 2D array using pointers.
Follow the given steps to implement the above code.
Ask the user to input the number of rows ( m ) and the number of columns ( n ) of the 2D array.
So the total number of elements of 1D array = ( m * n ) elements.
Call the function input_array to store elements in 1D array.
void input_array (int *arr,int size) // size = m * n
Call the function print_array to print the elements of 1D array.
void print_array (int *arr, int size)
Call the function array_to_matrix to convert 1D array to 2D array.
void array_to_matrix(int **matrix, int *arr, int row, int col)
Call function print_matrix to print the elements of the 2D array.
void print_matrix(int **mat, int row, int col)
All functions should be called from the main(). Accessing and storing of elements in pointers should be carried out by using pointers only.
Code:
#include <stdio.h>
#include <stdlib.h>
#define max 100
void input_array (int *arr,int size);
void print_array (int *arr, int size);
void array_to_matrix(int **matrix, int *arr, int row, int col);
void print_matrix(int **matrix, int row, int col);
int main()
{
int m, n, arr[max], mat[max][max];
printf("Enter the number of rows(m):");
scanf("%d",&m);
printf("Enter the number of columns(n):");
scanf("%d",&n);
int size = m*n;
input_array (arr,size);
print_array (arr,size);
array_to_matrix(mat, arr, m, n);
print_matrix(mat, m, n);
}
void input_array (int *arr,int size)
{
int i;
for(i=0;i<size;i++)
{
printf("Enter element a[%d]",i);
scanf("%d",&arr[i]);
}
}
void print_array (int *arr, int size)
{
int i;
printf("\n 1D array is as follows : \n");
for(i=0;i<size;i++)
{
printf("%d",arr[i]);
}
}
void array_to_matrix(int **matrix, int *arr, int row, int col)
{
int i,j,k=0;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
matrix[i][j] = arr[k];
k++;
}
}
}
void print_matrix(int **matrix, int row, int col)
{
int i,j;
printf("\n 2D matrix is as follows : \n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d ",matrix[i][j]);
}
printf("\n");
}
}
Error:
I am getting a segmentation fault. The problem I am having is related to pointer to the arrays and how to pass them to the function.
in
void main()
{
int m, n, arr[max], mat[max][max];
int size = m*n;
you compute size while m and n are not yet (possibly) initialized, so the value of size is undefined with undefined behavior
In
void array_to_matrix(int **matrix, int *arr, int row, int col)
{
int i,j,k=0;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
matrix[i][j] = arr[k];
}
}
}
the signature of the function says matrix is an array of pointers to int, but this is not compatible with your main where you use a 2D array. To be compatible :
void array_to_matrix(int (*matrix)[max], int *arr, int row, int col)
and same for print_matrix :
void print_matrix(int (*matrix)[max], int row, int col)
or if you prefer :
void array_to_matrix(int matrix[][max], int *arr, int row, int col)
void print_matrix(int matrix[][max], int row, int col)
But :
Write a C program to convert 1D array to 2D array using pointers
"2D array using pointers" is an is an abuse of language and means a 1D array of pointer to int, there is no 2D array.
In your previous version you limited the dimensions to 100, you do not have a reason to do that, just allocate the arrays in the heap.
Note also k always values 0 in array_to_matrix, so you always use arr[0]
And :
void main()
is wrong, main returns an int
I also encourage you to always check the result of scanf to be sure a valid input was used, else you works with non initialized value with an undefined behavior. When you read the number of rows and columns check there are not less than 1
In print_array to separate the print value with a space will help to make the result readable
Finaly :
#include <stdio.h>
#include <stdlib.h>
void input_array (int *arr,int size);
void print_array (int *arr, int size);
void array_to_matrix(int ** matrix, int *arr, int row, int col);
void print_matrix(int ** matrix, int row, int col);
int main()
{
int m, n, * arr, ** mat;
int size, i;
printf("Enter the number of rows(m):");
if ((scanf("%d",&m) != 1) || (m < 1)) {
puts("invalid value for rows");
return -1;
}
printf("Enter the number of columns(n):");
if ((scanf("%d",&n) != 1) || (n < 1)) {
puts("invalid value for columns");
return -1;
}
size = m*n;
if (((arr = malloc(size * sizeof(int))) == NULL) ||
((mat = malloc(m * sizeof(int))) == NULL)) {
puts("not enouh memory");
exit(-1);
}
for (i = 0; i < m; ++i) {
if ((mat[i] = malloc(n * sizeof(int))) == NULL) {
puts("not enouh memory");
exit(-1);
}
}
input_array (arr,size);
print_array (arr,size);
array_to_matrix(mat, arr, m, n);
print_matrix(mat, m, n);
/* free resources */
free(arr);
for (i = 0; i < m; ++i)
free(mat[i]);
free(mat);
return 0;
}
void input_array (int *arr,int size)
{
int i;
for(i=0;i<size;i++)
{
printf("Enter element a[%d]",i);
if (scanf("%d",&arr[i]) != 1) {
int c;
puts("invalid value, redo");
/* flush invalid value up to the end of line */
while ((c = getchar()) != '\n') {
if (c == EOF) {
puts("EOF, abort");
exit(-1);
}
}
i -= 1;
}
}
}
void print_array (int *arr, int size)
{
int i;
printf("\n 1D array is as follows : \n");
for(i=0;i<size;i++)
{
printf("%d ",arr[i]);
}
}
void array_to_matrix(int ** matrix, int *arr, int row, int col)
{
int i,j,k=0;
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
matrix[i][j] = arr[k++];
}
}
}
void print_matrix(int ** matrix, int row, int col)
{
int i,j;
printf("\n 2D matrix is as follows : \n");
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
printf("%d ",matrix[i][j]);
}
printf("\n");
}
}
Compilation and execution :
pi#raspberrypi:/tmp $ gcc -g -Wall c.c
pi#raspberrypi:/tmp $ ./a.out
Enter the number of rows(m):2
Enter the number of columns(n):aze
invalid value for columns
pi#raspberrypi:/tmp $ ./a.out
Enter the number of rows(m):-1
invalid value for rows
pi#raspberrypi:/tmp $ ./a.out
Enter the number of rows(m):2
Enter the number of columns(n):3
Enter element a[0]1
Enter element a[1]aa
invalid value, redo
Enter element a[1]2
Enter element a[2]3
Enter element a[3]4
Enter element a[4]5
Enter element a[5]6
1D array is as follows :
1 2 3 4 5 6
2D matrix is as follows :
1 2 3
4 5 6
pi#raspberrypi:/tmp $
I'm trying to print out the averages in the function void printavg(float *matrix,float *rowAve,float *colAve, float overallAve, int rows, int cols);
but when I tried to do a test run on printing out the average for rows I didn't get the right answer. What's the proper way to print out the avg using the printavg function. Here's an example of what the program should do:
Enter row dimension <must be between 1 and 5>: 3
Enter column dimension <must be between 1 and 5>: 2
Enter 6 data values for 3 x 2 matrix, in by-row order
1
2
3
4
5
6
1.00 2.00 1.50
3.00 4.00 3.50
5.00 6.00 5.50
3.00 4.00
Overall average is: 3.500000
Enter 0 to continue with a new matrix
Enter any other number to terminate the program:
Here's the code that I have so far
#include <stdio.h>
#include <stdlib.h>
// Function Prototypes
float *readMatrix(int rows, int cols);
float *rowavg(float *matrix, int rows, int cols);
float *colavg(float *matrix, int rows, int cols);
float overallavg(float* matrix, int rows, int cols);
void printavg(float *matrix, float *rowAve, float *colAve, float overallAve, int rows, int cols);
#define MAX_DIM 15
int main(void)
{
int done = 0;
int rows, cols;
float *dataMatrix;
float *rowAveVector;
float *colAveVector;
float overallAve;
while (!done)
{
// Prompt user to enter row and column dimensions of matrix (must be > 0)
do
{
printf("Enter row dimension (must be between 1 and %d): ", MAX_DIM);
scanf("%d", &rows);
} while(rows <= 0 || rows > MAX_DIM);
do
{
printf("Enter column dimension (must be between 1 and %d): ", MAX_DIM);
scanf("%d", &cols);
} while(cols <= 0 || cols > MAX_DIM);
dataMatrix = readMatrix(rows, cols);
if (dataMatrix == NULL)
{
printf ("Program terminated due to dynamic memory allocation failure\n");
return (0);
}
rowAveVector = rowavg(dataMatrix, rows, cols);
colAveVector = colavg(dataMatrix, rows, cols);
if(rowAveVector == NULL || colAveVector == NULL)
{
printf("malloc failed. Terminating program\n");
return (0);
}
overallAve = overallavg(dataMatrix, rows, cols);
//Print Averages
printAverages(dataMatrix, rowAveVector, colAveVector, overallAve, rows, cols);
free(dataMatrix);
free(rowAveVector);
free(colAveVector);
//Check if user wants to enter a new matrix
printf("Enter 0 to continue with a new matrix\n");
printf("Enter any other number to terminate the program: ");
scanf("%d", &done);
}
//That's it, we are done
return (0);
}
float *readMatrix(int rows, int cols)
{
int i=0;
int j=0;
int elements=0;
float *m=malloc(rows*cols*sizeof(float));
if (m==NULL)
{
printf("error\n");
return NULL;
}
printf("Enter values for the matrix: ");
for (i=0;i<rows;i++)
{
for (j=0;j<cols;j++)
{
elements = i*cols+j;
scanf("%f", &m[elements]);
}
}
return m;
}
float *rowavg(float *matrix, int rows, int cols)
{
if (matrix==NULL)
{
return NULL;
}
int i=0;
int j=0;
float mean=0;
float *Average_array=malloc(rows*sizeof(float));
if (Average_array==NULL)
{
return NULL;
}
for (i=0;i<rows;i++)
{
for (j=0;j<cols;j++)
{
mean+=matrix[i*cols+j];
}
Average_array[i]=(float)(mean/cols);
}
return Average_array;
}
float *colavg(float *matrix, int rows, int cols)
{
if (matrix==NULL)
{
return NULL;
}
int i=0;
int j=0;
float mean=0;
float *Average_array=malloc(cols*sizeof(float));
if (Average_array==NULL)
{
return NULL;
}
for (i=0;i<cols;i++)
{
for (j=0;j<rows;j++)
{
mean+=matrix[j*cols+i];
}
Average_array[i]=(float)(mean/rows);
}
return Average_array;
}
float overallavg(float* matrix, int rows, int cols)
{
float sum=0;
int i=0;
float elements=0;
float mean;
elements=rows*cols;
for (i=0;i<elements;i++)
{
sum+=matrix[i];
}
mean=sum/elements;
return mean;
}
void printavg(float *matrix, float *rowAve, float *colAve, float overallAve, int rows, int cols)
{
printf("%f",rowAve[rows,cols]);
}
Did I implement float overallavg(float* matrix, int rows, int cols)correctly? I think I didn't. I'm trying to return the average value of the elements of the array pointed to by matrix. Should I call the other two functions into the overall one and then divide by the total number elements in the array?
#include <stdio.h>
#include <stdlib.h>
float *readMatrix(int rows, int cols);
float *rowavg(float *matrix, int rows, int cols);
float *colavg(float *matrix, int rows, int cols);
float overallavg(float* matrix, int rows, int cols);
void printavg(float *matrix, float *rowAve, float *colAve, float overallAve, int rows, int cols);
#define MAX_DIM 10
int main(void)
{
int done = 0;
int rows, cols;
float *dataMatrix;
float *rowAveVector;
float *colAveVector;
float overallAve;
while (!done)
{
// Prompt user to enter row and column dimensions of matrix (must be > 0)
do
{
printf("Enter row dimension (must be between 1 and %d): ", MAX_DIM);
scanf("%d", &rows);
} while(rows <= 0 || rows > MAX_DIM);
do
{
printf("Enter column dimension (must be between 1 and %d): ", MAX_DIM);
scanf("%d", &cols);
} while(cols <= 0 || cols > MAX_DIM);
dataMatrix = readMatrix(rows, cols);
if (dataMatrix == NULL)
{
printf ("Program terminated due to dynamic memory allocation failure\n");
return (0);
}
rowAveVector = rowAverage(dataMatrix, rows, cols);
colAveVector = colAverage(dataMatrix, rows, cols);
if(rowAveVector == NULL || colAveVector == NULL)
{
printf("malloc failed. Terminating program\n");
return (0);
}
overallAve = overallAverage(dataMatrix, rows, cols);
//Print Averages
printAverages(dataMatrix, rowAveVector, colAveVector, overallAve, rows, cols);
free(dataMatrix);
free(rowAveVector);
free(colAveVector);
//Check if user wants to enter a new matrix
printf("Enter 0 to continue with a new matrix\n");
printf("Enter any other number to terminate the program: ");
scanf("%d", &done);
}
//That's it, we are done
return (0);
}
float *readMatrix(int rows, int cols)
{
int i=0;
int j=0;
int elements=0;
float *m=malloc(rows*cols*sizeof(float));
if (m==NULL)
{
printf("error\n");
return NULL;
}
printf("Enter values for the matrix: ");
for (i=0;i<rows;i++)
{
for (j=0;j<cols;j++)
{
elements = i*cols+j;
scanf("%f", &m[elements]);
}
}
return m;
}
float *readMatrix(int rows, int cols)
{
int i=0;
int j=0;
int elements=0;
float *m=malloc(rows*cols*sizeof(float));
if (m==NULL)
{
printf("error\n");
return NULL;
}
printf("Enter values for the matrix: ");
for (i=0;i<rows;i++)
{
for (j=0;j<cols;j++)
{
elements = i*cols+j;
scanf("%f", &m[elements]);
}
}
return m;
}
float *rowavg(float *matrix, int rows, int cols)
{
if (matrix==NULL)
{
return NULL;
}
int i=0;
int j=0;
float mean=0;
float *Average_array=malloc(rows*sizeof(float));
if (Average_array==NULL)
{
return NULL;
}
for (i=0;i<rows;i++)
{
for (j=0;j<cols;j++)
{
mean+=matrix[i*cols+j];
}
Average_array[i]=(float)(mean/cols);
}
return Average_array;
}
float *colavg(float *matrix, int rows, int cols)
{
if (matrix==NULL)
{
return NULL;
}
int i=0;
int j=0;
float mean=0;
float *Average_array=malloc(cols*sizeof(float));
if (Average_array==NULL)
{
return NULL;
}
for (i=0;i<cols;i++)
{
for (j=0;j<rows;j++)
{
mean+=matrix[j*cols+i];
}
Average_array[i]=(float)(mean/rows);
}
return Average_array;
}
float overallavg(float* matrix, int rows, int cols)
{
if (matrix==NULL)
{
return NULL;
}
int i=0;
int j=0;
float mean_1=0;
float mean_2=0;
float avg=0;
float elements=0;
float sum=0;
elements=rows*cols;
for (i=0;i<rows;i++)
{
for (j=0;j<cols;j++)
{
mean_1+=matrix[i*rows+j];
}
}
for (i=0;i<cols;i++)
{
for (j=0;j<rows;j++)
{
mean_2+=matrix[j*cols+i];
}
}
sum=mean_1+mean_2;
avg=sum/elements-1;
}
the following code:
cleanly compiles
contains the needed #include statements
Note: this line:
avg=sum/elements-1;
will not calculate the average of all the elements but rather a somewhat larger value because the total number of elements is being decremented by 1
Suggestion, in the function: overallavg() do not calculate separate 'mean' values, rather simply step through the whole array summing each element, then divide by the total number of elements
Suggestion, use an indent width of 4 spaces, as that is easily visible, even with a variable width font. 2 spaces with a variable width font just looks like the indented row is indented about 1/2 the width of a char. I.E. barely visible and very messy looking. (code is read many many times so should be written to be very easy to read.
#include <stdio.h> // printf() scanf()
#include <stdlib.h> // malloc, free()
float *readMatrix( size_t rows, size_t cols)
{
//int i=0;
//int j=0;
size_t elements=0;
float *m=malloc(rows*cols*sizeof(float));
if (m==NULL)
{
printf("error\n");
return NULL;
}
printf("Enter values for the matrix: ");
for (size_t i=0; i<rows; i++)
{
for ( size_t j=0; j<cols; j++)
{
elements = i*cols+j;
scanf("%f", &m[elements]);
}
}
return m;
}
float *rowavg(float *matrix, size_t rows, size_t cols)
{
if (matrix==NULL)
{
return NULL;
}
//int i=0;
//int j=0;
float mean=0;
float *Average_array=malloc(rows*sizeof(float));
if (Average_array==NULL)
{
return NULL;
}
for ( size_t i=0; i<rows; i++)
{
for ( size_t j=0; j<cols; j++)
{
mean+=matrix[i*cols+j];
}
Average_array[i] = (mean/(float)cols);
}
return Average_array;
}
float *colavg(float *matrix, size_t rows, size_t cols)
{
if (matrix==NULL)
{
return NULL;
}
//int i=0;
//int j=0;
float mean=0;
float *Average_array = malloc( cols*sizeof(float) );
if (Average_array==NULL)
{
return NULL;
}
for ( size_t i=0; i<cols; i++)
{
for (size_t j=0; j<rows; j++)
{
mean+=matrix[j*cols+i];
}
Average_array[i] = (mean/(float)rows);
}
return Average_array;
}
float overallavg(float* matrix, size_t rows, size_t cols)
{
#if 0
if (matrix==NULL)
{
return NULL;
}
#endif
//int i=0;
//int j=0;
float mean_1=0;
float mean_2=0;
float avg=0;
float elements=0;
float sum=0;
elements= (float)rows* (float)cols;
for ( size_t i=0;i<rows;i++)
{
for ( size_t j=0;j<cols;j++)
{
mean_1+=matrix[i*rows+j];
}
}
for ( size_t i=0; i<cols; i++)
{
for ( size_t j=0; j<rows ;j++)
{
mean_2+=matrix[j*cols+i];
}
}
sum=mean_1+mean_2;
avg=sum/elements-1;
return avg;
}
I am trying to allocate a matrix using a function that takes its dimensions and a triple pointer. I have allocated an int** (set to NULL) and I am passing its address as the function's argument. That gives me a mem access violation for some reason.
void allocateMatrix(int ***matrix, int row, int col)
{
int i;
if((*matrix = (int**)malloc(row * sizeof(int*))) == NULL)
{
perror("There has been an error");
exit(EXIT_FAILURE);
}
for(i = 0; i < row; ++i)
{
if((*matrix[i] = (int*)malloc(col * sizeof(int))) == NULL)
{
perror("There has been an error");
exit(EXIT_FAILURE);
}
}
}
/* main.c */
int** matrix = NULL;
allocateMatrix(&matrix, MATRIX_ROW, MATRIX_COL); //error
You need to change
if((*matrix[i] = (int*)malloc(col * sizeof(int))) == NULL)
to
if(((*matrix)[i] = (int*)malloc(col * sizeof(int))) == NULL)
// ^ ^
You need to dereference matrix before using the array subscript.
*matrix[i] is equivalent to *(matrix[i])
It's a problem of operator precedence. In
if ((*matrix[i] = (int*)malloc( ... ))
the default precedence is *(matrix[i]), while you should use (*matrix)[i].
I would still recommend to allocate the matrix as a contiguous array instead as a array of pointers to arrays.
I have made a solution program for gcc C11/C99 with apropriate allocation funtions based on links:
http://c-faq.com/aryptr/dynmuldimary.html
http://c-faq.com/aryptr/ary2dfunc3.html
After some discussion in comments, it is clear that matrix2 is correctly allocated, it can be passed to this function fn(int row, int col, int array[col][row]) as matrix2[0] (data in one dimensional array) with a cast to (double (*)[])
//compile with gcc --std=c11 program.c
#include <stdio.h>
#include <stdlib.h>
#define MX 9
#define MY 14
void input_matrix(int row, int column, double matrix[row][column]);
void print_matrix(int row, int column, double matrix[row][column]);
double **alloc_matrix2(int row, int column);
double *alloc_matrix3(int row, int column);
void *alloc_matrix4(int row, int column);
int main()
{
int i=MX, j=MY;
printf("Generate input values and print matrices with functions fn(int w, int k, double matrix[w][k]) (in C99 and C11)\n");
double matrix1[i][j];
input_matrix(MX,MY,matrix1);
printf("matrix static\n");
print_matrix(MX,MY,matrix1);
double **matrix2; //data of matrix2 is just matrix3
matrix2=alloc_matrix2(MX,MY);
input_matrix(MX,MY,(double (*)[])(*matrix2));
printf("matrix two times allocated one for pointers, the second for data (double (*)[])(m[0])\n");
print_matrix(MX,MY,(double (*)[])(matrix2[0]));
free(*matrix2);
free(matrix2);
double *matrix3=alloc_matrix3(MX,MY);
input_matrix(MX,MY,(double (*)[])matrix3);
printf("matrix allocated as two-dimensional array\n");
print_matrix(MX,MY,(double (*)[])matrix3);
free(matrix3);
j=MY;
double (*matrix4)[j];
matrix4 = (double (*)[])alloc_matrix4(MX,MY);
input_matrix(MX,MY,matrix4);
printf("matrix allocated via pointer to array m = (double (*)[])malloc(MX * sizeof(*m))\n");
print_matrix(MX,MY,matrix4);
free(matrix4);
printf("\nThe End!\n");
return 0;
}
void input_matrix(int row, int column, double matrix[row][column]){
for(int i=0; i<row; i++){
for(int j=0; j<column; j++)
matrix[i][j]=i+1;
}
}
void print_matrix(int row, int column, double matrix[row][column]){
for(int i=0; i<row; i++){
for(int j=0; j<column; j++)
printf("%.2lf ", matrix[i][j]);
printf("\n");
}
}
double **alloc_matrix2(int row, int column){
double **matrix;
matrix=malloc(row*sizeof(double*));
matrix[0] = (double *)malloc(row*column*sizeof(double));
for(int i = 1; i < row; i++)
matrix[i] = matrix[0]+i*column;
return matrix;
}
double *alloc_matrix3(int row, int column){
double *matrix;
matrix=malloc(row*column*sizeof(double));
return matrix;
}
void *alloc_matrix4(int row, int column){
double (*matrix)[column];
matrix = (double (*)[])malloc(row*sizeof(*matrix));
return matrix;
}
I've been trying this code and it's not working out very well.
void *matrix_allocate_variable (int size)
{
void *p1;
if ((p1=(int*)malloc(size))==NULL){
printf("out of memory.\n");
exit(1);
}
return p1;
}
Here I created a function that call's malloc and exits upon error, so that I could use it in my next function:
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]);
Here is where I am having problems. I'm trying to have the user enter some input for creating the matrix, but I'm having lots of problems trying to get this working. Can some one help me start this off?
PS. For more details, I'm creating functions in functions.c, this are what I have so far. I have a main.c which calls these functions so that later on I can add, subract, and transpose, but as of now I am trying to enter in data which is what I'm having lot of trouble with. Here is my main.c where I call the functions.
/* 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;
}
Any help will be good and any pointers in what I should do next is great also. Thank you so so much every one.
Hi this is a sample code to create one matrix using malloc.
(This should give you some insight on how to create an array of matrices. If it doesn't then let me know.)
#include <stdio.h>
#include <stdlib.h>
// Creates a matrix given the size of the matrix (rows * cols)
int **CreateMatrix(int rows, int cols) {
int **matrix = malloc(sizeof(int*) * rows);
int row;
for (row = 0; row < rows; row++) {
matrix[row] = malloc(sizeof(int) * cols);
}
return matrix;
}
// Take input for the matrix.
void MatrixInput(int **matrix, int rows, int cols) {
int row, col;
for (row = 0; row < rows; row++) {
for (col = 0; col < cols; col++) {
scanf("%d", &matrix[row][col]);
}
}
}
void PrintMatrix(int **matrix, int rows, int cols) {
int row, col;
for (row = 0; row< rows; row++) {
for (col = 0; col < cols; col++) {
printf("%d ", matrix[row][col]);
}
printf("\n");
}
}
int main() {
int **matrix;
int rows = 5;
int cols = 4;
matrix = CreateMatrix(rows, cols);
MatrixInput(matrix, rows, cols);
PrintMatrix(matrix, rows, cols);
}
Here is an example of creating and freeing memory for a two dimendional array...
(easily modifiable for other types)
int ** Create2D(int **arr, int cols, int rows)
{
int space = cols*rows;
int y;
arr = calloc(space, sizeof(int));
for(y=0;y<cols;y++)
{
arr[y] = calloc(rows, sizeof(int));
}
return arr;
}
void free2DInt(int **arr, int cols)
{
int i;
for(i=0;i<cols; i++)
if(arr[i]) free(arr[i]);
free(arr);
}
Use it like this:
#include <ansi_c.h>
int main(void)
{
int **array=0, i, j;
array = Create2D(array, 5, 4);//get the actual row/column values from reading the file once.
for(i=0;i<5;i++)
for(j=0;j<4;j++)
array[i][j]=i*j; //example values for illustration
free2DInt(array, 5);
return 0;
}