I have been looking for a way to swap the names between two matrices in C. I have 2 square size x size matrices. I make some operation to the one of them, I put the result in a cell in the other matrix, then I swap their names and I repeat.
Below I am giving my code
int main(void){
int const size = 1000;
int const steps = 10;
float A[size][size], B[size][size];
int i,j,k;
int t = 0;
double sum = 0;
double sum1 = 0;
int const ed = size - 1;
for(i = 0; i < size; ++i){
for(j = 0; j < size; ++j){// initialize the matrices
A[i][j] = i+j;
B[i][j] = 0;
}
}
for(i = 0; i < size; ++i){//find the sum of the values in the first matrix
for(j = 0; j < size; ++j){
sum = sum + A[i][j];
}
}
printf("The total sum of the matrix 1 is %lf \n",sum);
for(k = 0; k < steps; ++k){//for each cell of the matrix A calculate the average of the values' of the cell and its surroundings and put it in the coresponding place in the matrix B and then copy matrix B to matrix A and repeat. There are special cases for the cells who are at the edges and the last or first row/column.
for(i = 0; i < size; ++i){
for(j = 0; j < size; ++j){
if(i==0){
if(j==0)
B[i][j]=(A[0][0]+A[0][1]+A[0][ed]+A[1][0]+A[ed][0])/5.0;
else if(j==ed)
B[i][j]=(A[0][ed]+A[0][0]+A[0][ed-1]+A[1][ed]+A[ed][ed])/5.0;
else
B[i][j]=(A[0][j]+A[0][j+1]+A[0][j-1]+A[1][j]+A[ed][j])/5.0;
}else if(i==ed){
if(j==0)
B[i][j]=(A[ed][0]+A[ed][1]+A[ed][ed]+A[0][0]+A[ed-1][0])/5.0;
else if(j==ed)
B[i][j]=(A[ed][ed]+A[ed][0]+A[ed][ed-1]+A[0][ed]+A[ed-1][ed])/5.0;
else
B[i][j]=(A[ed][j]+A[ed][j+1]+A[ed][j-1]+A[0][j]+A[ed-1][j])/5.0;
}else{
if(j==0)
B[i][j]=(A[i][0]+A[i][1]+A[i][ed]+A[i+1][0]+A[i-1][0])/5.0;
else if(j==ed)
B[i][j]=(A[i][ed]+A[i][0]+A[i][ed-1]+A[i+1][ed]+A[i-1][ed])/5.0;
else
B[i][j]=(A[i][j]+A[i][j+1]+A[i][j-1]+A[i+1][j]+A[i-1][j])/5.0;
}
}
}
sum1 = 0;
for(i = 0; i < size; ++i){
for(j = 0; j < size; ++j){
sum1 = sum1 + B[i][j];
}
}
t=t+1;
for(i = 0; i < size; ++i){
for(j = 0; j < size; ++j){
A[i][j] = B[i][j];
}
}
printf("%lf \n",sum1-sum);
}
printf("The total sum of the matrix 2 is %lf \n",sum1);
printf("Number of steps completed: %i \n",t);
printf("Number of steps failed to complete: %i \n", steps-t);
return 0;
}
I have used the method of copying each time the one matrix to the other, but this is not efficient.
I have a hint that I should use pointers but I can not figure it out. Any help will be much appreciated.
You can swap the values of any two variables of the same type by assigning the value of the first to a temporary variable then assigning the value of the second to the first, then assigning the value of the temporary variable to the second:
int a = 2, b = 3, tmp;
tmp = a;
a = b;
b = tmp;
In particular, it works exactly the same when the variables are of pointer type, so
/* The matrices */
double one[3][3], another[3][3];
/* pointers to the matrices */
double (*matrix1p)[3] = one;
double (*matrix2p)[3] = another;
double (*tmp)[3];
/* ... perform matrix operations using matrix1p and matrix2p ... */
/* swap labels (pointers): */
tmp = matrix1p;
matrix1p = matrix2p;
matrix2p = tmp;
/* ... perform more matrix operations using matrix1p and matrix2p ... */
Updated to clarify:
matrix1p is initially an alias for one, and matrix2p is initially an alias for another. After the swap, matrix1p is an alias for another, whereas matrix2p is an alias for one. Of course, you can perform such a swap as many times as you want. You cannot, however, swap one and another themselves, except via an element-by-element swap.
Note that this yields improved efficiency because pointers are quite small relative to the matrices themselves. You don't have to move the elements of the matrices, but only to change which matrix each pointer refers to.
Yes, you should definitely use pointers, for example:
void swap (int*** m1, int*** m2)
{
int** temp;
temp = *m1;
*m1 = *m2;
*m2 = temp;
}
And then invoke:
int m1[5][5] = 0;
int m2[5][5] = 0;
swap (&m1, &m2);
Related
I have the following 2D array:
int censusData[4][3] = {{87290, 77787, 55632},
{83020, 78373, 62314},
{95588, 87934, 705421},
{112456, 97657, 809767}};
I want to print values column-wise in that, after 3 passes of a loop, it would print:
87290 83020 95588 112456
77787 78373 87934 97657
55632 62314 705421 809767
Notice how it's the first element from each sub-array, then the 2nd, then the third..etc
I can easily access each subarray when going row-wise using this:
int* averageCityIncome(int size, int size_2, int arr[][size_2]){
int* t_arr = malloc(4 * sizeof(int));
for (int i = 0; i < size; i++){
int avg = 0;
for (int j = 0; j < size_2; j++){
avg += arr[i][j];
}
avg /= size_2;
t_arr[i] = avg;
}
return t_arr;
}
But now I'm trying to read column-wise as stated above and I so far have this:
int* averageIncome(int size, int size_2, int arr[][size_2]){
int* t_arr = malloc(4 * sizeof(int));
for (int i = 0; i < size_2; i++){
for (int j = 0; j < size; j++){
printf("%d\n", arr[i][j]);
}
printf("-----\n");
}
return t_arr;
}
But it doesn't seem to be working. I'm still pretty new to C, and it's difficult to wrap my mind around 2D arrays still. Any help would be greatly appreciated.
You simply need to swap i and j for the dimensions when addressing a certain element of the array in the caller.
int* averageIncome(int size, int size_2, int arr[][size_2]) {
int* t_arr = calloc(4, sizeof(int)); // calloc to initialize the array elements to 0.
if ( t_arr == NULL )
{
fputs("Error at memory allocation for t_arr!", stderr);
exit(1);
}
int avg = 0; // definition of avg placed outside of the loop.
for (int i = 0; i < size_2; i++) {
for (int j = 0; j < size; j++) {
printf("%d\n", arr[j][i]); // j swapped with i.
avg += arr[j][i]; // same here too.
}
printf("-----\n");
t_arr[i] = avg / size;
avg = 0;
}
return t_arr;
}
Example (Online):
#include <stdio.h>
#include <stdlib.h>
#define ROWS 4
#define COLS 3
int* averageIncome(int size, int size_2, int arr[][size_2]) {
int* t_arr = calloc(4, sizeof(int)); // calloc to initialize the array elements to 0.
int avg = 0; // definition of avg placed outside of the loop.
for (int i = 0; i < size_2; i++) {
for (int j = 0; j < size; j++) {
printf("%d\n", arr[j][i]); // j swapped with i.
avg += arr[j][i]; // same here too.
}
printf("-----\n");
t_arr[i] = avg / size;
avg = 0;
}
return t_arr;
}
int main (void)
{
int censusData[ROWS][COLS] = {
{87290, 77787, 55632},
{83020, 78373, 62314},
{95588, 87934, 705421},
{112456, 97657, 809767}
};
int* p = averageIncome(ROWS, COLS, censusData);
for ( int i = 0; i < COLS; i++ )
{
printf("Average Income of %d. column is: %d\n", i + 1, p[i]);
}
return 0;
}
Output:
87290
83020
95588
112456
-----
77787
78373
87934
97657
-----
55632
62314
705421
809767
-----
Average Income of 1. column is: 94588
Average Income of 2. column is: 85437
Average Income of 3. column is: 408283
Side notes:
Always check the returned pointer from a memory-management for a null pointer if the allocation failed.
I used calloc() instead of malloc() to initialize all elements of the dynamically allocated array to 0.
The definition of avg should be placed before the nested loops, not within. Reset avg to 0 at the end of the outer loop.
avg /= size_2; t_arr[i] = avg; should be avg /= size; t_arr[i] = avg;. Note the replacement of size_2 with size.
avg /= size; t_arr[i] = avg; can be simplified by t_arr[i] = avg / size;.
#include <stdio.h>
int censusData[4][3] = {{87290, 77787, 55632},
{83020, 78373, 62314},
{95588, 87934, 705421},
{112456, 97657, 809767}};
int main() {
int* t_arr = malloc(3 * sizeof(int));
for(int i=0;i<3;i++){
int avg = 0;
for(int j=0;j<4;j++){
//Keep the I fixed here now J is varying and its position of column
//So you are reading all column values for ith row.
avg+=censusData[j][i];
}
avg/=4;
t_arr[i] = avg;
}
for(int i=0;i<3;i++){
printf("%d,",t_arr[i]);
}
return 0;
}
You can loop over the columns first and then print the corresponding element of each row:
for (int col = 0; col < 3; ++col)
{
for (int row = 0; row < 4; ++row)
{
printf("%d\n", censusData[row][col]);
// Do other stuff here
}
printf("-----\n");
}
For each row, the colth element is printed. So for col = 0, censusData[0][0], censusData[1][0], censusData[2][0], censusData[3][0] will be printed.
In your code, you can just swap the positions of the two for loops to iterate over the columns first.
I'm trying to multiply two dynamic matrices by passing them through a function. I'm getting a segmentation fault during the multiplication.
The matrices are being passed through a function. The items in the arguments are correct because I had to use them for a different operation in this project. I have a feeling that I messed up with the pointers, but i'm pretty new to C and i'm not sure where I messed up.
double** multiplyMatrices(
double** a,
const uint32_t a_rows,
const uint32_t a_cols,
double** b,
const uint32_t b_cols){
uint32_t i = 0;
uint32_t j = 0;
uint32_t k = 0;
double** c;
//allocate memory to matrix c
c = (double **)malloc(sizeof(double *) * a_rows);
for (i = 0; i < a_rows; i++) {
*(c +i) = (double *)malloc(sizeof(double) * b_cols);
}
//clear matrix c
for(i = 0; i < a_rows; i++){
for(j = 0; j < a_cols; j++){
*c[j] = 0;
}
}
i = 0;
//multiplication
while(j = 0, i < a_rows ){
while(k = 0, j < b_cols){
while(k < a_cols){
//following line is where i'm getting the segmentation fault
*(*(c+(i*b_cols))+j) += (*(*(a+(i*a_cols))+k)) * (*(*(b+(k*b_cols))+j));
k++;
}
j++;
}
i++;
}
return c;
}
The obvious mistake is that you dereference c + i * b_cols while c is an array of pointers of size a_rows. So likely c + i * b_cols is outside of the area that you previously allocated with malloc().
I would suggest to simplify the matrix representation using a single array of double with the size equal to the total number of elements, i.e. rows * cols.
For example:
double *c;
c = malloc(sizeof(double) * a_rows * b_cols);
This not only has better overall performance, but simplifies the code. You would then have to "linearise" the offset inside your unidimensional array to convert from bi-dimensional matrix coordinates. For example:
c[i * b_cols + j] = ...
Of course, the other two matrices need to be allocated, filled and accessed in a similar manner.
For code clarity, I would also replace the while statements by for statements with the actual variable that they loop on. For example:
for (i = 0; i < a_rows; i++)
for (j = 0; j < b_cols; j++)
for (k = 0; k < a_cols; k++)
You can (ab)use the C language in many ways, but the trick is to make it more clear for you in the first place.
This code should multiply matrix A with matrix B and calculate matrix C.
matA 3x2, matB 2x3 therefore matC should be `3x3.
However, when I print matC, the 3rd row contains garbage values.
I don't know where the mistake is — if I do something wrong with the pointers or maybe the calculate part is wrong.
This is what I see when printing it.
x x 2489458943
x x 2489587641
x x 2489745734
Or something like that.
I don't know why sometimes it works.
I mean it prints the correct values, but most of the time this is what I see.
#include <stdio.h>
int main() {
int x = 0,y = 0, z = 0;
int i,j,k;
int **matA;
int **matB;
int **matC;
matA = (int**)malloc(sizeof(int)*3); // making the matrixes by malloc functions
matB = (int**)malloc(sizeof(int)*2);
matC = (int**)malloc(sizeof(int)*3);
for(i = 0; i < 3; i ++)
{
matA[i] = (int*)malloc(sizeof(int)*2); // matA 3x2
}
for(i = 0; i < 2; i++)
{
matB[i] = (int*)malloc(sizeof(int)*3); // matB 2x3
}
for(i = 0; i < 3; i++)
{
matC[i] = (int*)malloc(sizeof(int)*3); // the calculated mat 3x3
}
for(i = 0; i < 3; i++)
{
printf("please eneter line number: %i",i+1); //putting the values by scanf function in matA
printf(" seperated with ','\n");
scanf("%d,%d",&x,&y);
matA[i][0] = x;
matA[i][1] = y;
}
for(i = 0; i < 2; i++)
{
printf("please eneter line number: %i",i+1);// putting the values in matB
printf(" of the second mat seperated with ','");
scanf("%i,%i,%i", &x, &y, &z);
matB[i][0] = x;
matB[i][1] = y;
matB[i][2] = z;
}
for(i = 0; i < 3; i++) // multiple the matrixes by 3 loops
{
for(j = 0; j < 3; j++)
{
for(k = 0; k < 2; k++)
{
matC[j][i] += matA[j][k]*matB[k][i];
}
}
}
for(i = 0; i < 3; i ++)// just printing to check if the matrix correct
{
for(j = 0; j < 3; j++)
{
printf("%i ",(int**)matC[i][j]);
}
printf("\n");
}
return 0;
}
You're not allocating enough space in your matrixes:
matA = (int**)malloc(sizeof(int)*3);
matB = (int**)malloc(sizeof(int)*2);
matC = (int**)malloc(sizeof(int)*3);
You're allocating space for an array int but you need an array of int *. Most likely, pointers are larger than integers on your system which means your arrays aren't large enough to hold what you want and you run of the end of the array. Doing so invokes undefined behavior.
Allocate space for arrays of int *. Also, don't cast the return value of malloc:
matA = malloc(sizeof(int *)*3);
matB = malloc(sizeof(int *)*2);
matC = malloc(sizeof(int *)*3);
You're also adding to elements of matC without initializing them. You should set them to 0 before doing so:
matC[j][i] = 0;
for(k = 0; k < 2; k++)
{
matC[j][i] += matA[j][k]*matB[k][i];
}
You also don't need a cast here:
printf("%i ",(int**)matC[i][j]);
Since each matC[i][j] has type int and you're printing an int. This also invokes undefined behavior because the type of the expression doesn't match the type for the format specifier.
You never initialize matC and then use matC +=
The malloc function allocates size bytes and returns a pointer to the allocated memory. The memory is not initialized. Try calloc instead.
Also, you have wrong int** initialization, should allocate pointer size sizeof(int*), not just sizeof(int):
matA = (int**)calloc(3, sizeof(int*));
matB = (int**)calloc(2, sizeof(int*));
matC = (int**)calloc(3, sizeof(int*));
I want to store a lower triangular matrix in memory, without storing all the zeros.
The way I have implemented it is by allocating space for i + 1 elements on the ith row.
However, I am new to dynamic memory allocation in C and something seems to be wrong with my first allocation.
int main ()
{
int i, j;
int **mat1;
int dim;
scanf("%d", &dim);
*mat1 = (int**) calloc(dim, sizeof(int*));
for(i = 0; i < dim; i++)
mat1[i] = (int*) calloc(i + 1, sizeof(int));
for(i = 0; i < dim; i++)
{
for(j = 0; j < i + 1; j++)
{
scanf("%d", &mat1[i][j]);
}
}
/* Print the matrix without the zeros*/
for(i = 0; i < dim; i++)
{
for(j = 0; j < (i + 1); j++)
{
printf("%d%c", mat1[i][j], j != (dim-1) ? ' ' : '\n');
}
}
return 0;
}
If you want to conserve space and the overhead of allocating every row of the matrix, you could implement a triangular matrix by using clever indexing of a single array.
A lower triangular matrix (including diagonals) has the following properties:
Dimension Matrix Elements/row Total elements
1 x . . . 1 1
2 x x . . 2 3
3 x x x . 3 6
4 x x x x 4 10
...
The total number of elements for a given dimension is:
size(d) = 1 + 2 + 3 + ... + d = (d+1)(d/2)
If you lay the rows out consecutively in a single array, you can use the formula above to calculate the offset of a given row and column (both zero-based) inside the matrix:
index(r,c) = size(r-1) + c
The formulas above are for the lower triangular matrix. You can access the upper matrix as if it was a lower matrix by simply reversing the indexes:
index((d-1)-r, (d-1)-c)
If you have concerns about changing the orientation of the array, you can devise a different offset calculation for the upper array, such as:
uindex(r,c) = size(d)-size(d-r) + c-r
Sample code:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#define TRM_SIZE(dim) (((dim)*(dim+1))/2)
#define TRM_OFFSET(r,c) (TRM_SIZE((r)-1)+(c))
#define TRM_INDEX(m,r,c) ((r)<(c) ? 0 : (m)[TRM_OFFSET((r),(c))])
#define TRM_UINDEX(m,r,c,d) ((r)>(c)?0:(m)[TRM_SIZE(d)-TRM_SIZE((d)-(r))+(c)-(r)])
#define UMACRO 0
int main (void)
{
int i, j, k, dimension;
int *ml, *mu, *mr;
printf ("Enter dimension: ");
if (!scanf ("%2d", &dimension)) {
return 1;
}
ml = calloc (TRM_SIZE(dimension), sizeof *ml);
mu = calloc (TRM_SIZE(dimension), sizeof *mu);
mr = calloc (dimension*dimension, sizeof *mr);
if (!ml || !mu || !mr) {
free (ml);
free (mu);
free (mr);
return 2;
}
/* Initialization */
srand (time (0));
for (i = 0; i < TRM_SIZE(dimension); i++) {
ml[i] = 100.0*rand() / RAND_MAX;
mu[i] = 100.0*rand() / RAND_MAX;
}
/* Multiplication */
for (i = 0; i < dimension; i++) {
for (j = 0; j < dimension; j++) {
for (k = 0; k < dimension; k++) {
mr[i*dimension + j] +=
#if UMACRO
TRM_INDEX(ml, i, k) *
TRM_UINDEX(mu, k, j, dimension);
#else
TRM_INDEX(ml, i, k) *
TRM_INDEX(mu, dimension-1-k, dimension-1-j);
#endif
}
}
}
/* Output */
puts ("Lower array");
for (i = 0; i < dimension; i++) {
for (j = 0; j < dimension; j++) {
printf (" %2d", TRM_INDEX(ml, i, j));
}
putchar ('\n');
}
puts ("Upper array");
for (i = 0; i < dimension; i++) {
for (j = 0; j < dimension; j++) {
#if UMACRO
printf (" %2d", TRM_UINDEX(mu, i, j, dimension));
#else
printf (" %2d", TRM_INDEX(mu, dimension-1-i, dimension-1-j));
#endif
}
putchar ('\n');
}
puts ("Result");
for (i = 0; i < dimension; i++) {
for (j = 0; j < dimension; j++) {
printf (" %5d", mr[i*dimension + j]);
}
putchar ('\n');
}
free (mu);
free (ml);
free (mr);
return 0;
}
Note that this is a trivial example. You could extend it to wrap the matrix pointer inside a structure that also stores the type of the matrix (upper or lower triangular, or square) and the dimensions, and write access functions that operate appropriately depending on the type of matrix.
For any non-trivial use of matrices, you should probably use a third-party library that specializes in matrices.
mat1 = calloc(dim,sizeof(int*));
mat1 is a double pointer.You need to allocate memory for your array of pointers and later you need to allocate memory to each of your pointers individually.No need to cast calloc()
You are dereferencing mat1 at line 8 before it has even been set to point anywhere. You are allocating an array of pointers to int, but you are not assigning that to mat1 but to the dereference of mat1, which is uninitialized, we don't know what it points to.
So this line:
// ERROR: You are saying an unknown memory location should have the value of calloc.
*mat1 = (int**)calloc(dim,sizeof(int*));
Should change to:
// OK: Now you are assigning the allocation to the pointer variable.
mat1 = (int**)calloc(dim,sizeof(int*));
I'm trying to multiply two multidimensional arrays to form a matrix. I have this function. This should work in theory. However, I am just getting 0s and large/awkward numbers. Can someone help me with this?
int **matrix_mult( int **a, int **b, int nr1, int nc1, int nc2 )
{
int **c;
int i,j,k,l;
c = malloc(sizeof(int *)*nr1);
if (c == NULL){
printf("Insuff memm");
}
for(l=0;l<nr1;l++){
c[l] = malloc(sizeof(int)*nc1);
if (c[l] == NULL){
printf("Insuff memm");
}
}//for loop
for (i=0;i<nr1;i++){
for (j=0;j<nc2;j++){
for (k=0;k<nc1;k++){
c[i][j] = (a[i][k]) * (b[k][j]);
}
}
}
return( c );
}
Are you doing mathematical matrix multiplication? If so shouldn't it be:
for(i = 0; i < nr1; i++)
{
for(j = 0; j < nc1; j++)
{
c[i][k] = 0;
for(k = 0; k < nc2; k++)
{
c[i][k] += (a[i][j]) * (b[j][k]);
}
}
}
My full and final solution, tested to produce sensible results (I didn't actually do all the calculations myself manually to check them) and without any sensible niceties such as checking memory allocations work, is:
int **matrix_mult(int **a, int **b, int nr1, int nc1, int nc2)
{
int **c;
int i, j, k;
c = malloc(sizeof(int *) * nr1);
for (i = 0; i < nr1; i++)
{
c[i] = malloc(sizeof(int) * nc2);
for (k = 0; k < nc2; k++)
{
c[i][k] = 0;
for (j = 0; j < nc1; j++)
{
c[i][k] += (a[i][j]) * (b[j][k]);
}
}
}
return c;
}
There were a few typos in the core of the for loop in my original answer, mostly due to my being mislead by a different answer. These have been corrected for posterity.
If you change c[i][j] = (a[i][k]) * (b[k][j]); to c[i][j] += (a[i][k]) * (b[k][j]); in your code then it will work just fine provided that
nr1 is number of rows of matrix a
nc1 is the number of columns of the matrix a
nc2 is the number of columns of the matrix b
Just be sure that the matrix c is initiated with zeroes. You can just use calloc instead of malloc when allocating space, or memset the allocated array after a call to malloc.
One more tip is to avoid using the letter l when accessing array elements. when tired, you will have hard time noticing errors with l vs 1.