I have a matrix structure (for storing squared matrices)
which is defined as

``````typedef struct
{
int **matrix;
int format;
}MATRIX;
``````

How to add 'n' number of matrices?

Edited by Dani: Fixed bug where you can now have 1-letter tags so no more need to preface with C

2
Contributors
3
Replies
26
Views
1 Year
Discussion Span
Last Post by gusano79

Same as you'd add n numbers: Initialize a "sum" matrix to all zeros, then add matrices 1..n to the sum.

@gusano79 Could you check the code (I have some segmentation faults, can't find what is wrong).
Also, could you show (in the code) how to add 'n' matrices?

``````#include<stdio.h>
#include<stdlib.h>
#define MAX 10
typedef struct
{
int **matrix;
int format;
}MATRIX;
{
do
{
printf("format=");
scanf("%d",&pm->format);
}
while(pm->format < 1 || pm->format > MAX);
pm->matrix=(int **)calloc(pm->format,sizeof(int *));
int i,j,b=0;
for(i=0;i<pm->format;i++)
{
pm->matrix[i]=(int *)calloc(pm->format,sizeof(int));
for(j=0;j<pm->format;j++,b++)
pm->matrix[i][j]=b;
}
for(i=0;i<pm->format;i++)
for(j=0;j<pm->format;j++)
{
printf("mat[%d][%d]",i,j);
scanf("%d",&pm->matrix[i][j]);
}
}

{
array=(MATRIX *)malloc(*n * sizeof(MATRIX));
do
{
printf("number of matrices:");
scanf("%d",n);
}
while(*n < 1);
int i;
for(i=0;i<*n;i++)
{
}
}

void print(MATRIX *pm)
{
int i,j;
for(i=0;i<pm->format;i++){
for(j=0;j<pm->format;j++){
printf("%d\t",pm->matrix[i][j]);
}
printf("\n");
}
}

void erase_1(MATRIX *pm)
{
int i;
for(i=0;i<pm->format;i++)
free(pm->matrix[i]);
free(pm->matrix);
}

int main()
{
MATRIX *array;
MATRIX *result;
int i,n;
for(i=0;i<n;i++)
{
printf("%d. matrix:\n",i+1);
}
print(res);
for(i=0;i<n;i++)
erase_1(array+i);
free(array);
free(res);
return 0;
}
``````

First things first...

How is this even compiling? You use the name `res` which isn't defined anywhere; I assume you mean `result`.

I have some segmentation faults, can't find what is wrong

What compiler are you using? Does it report any warnings? It should.

VS2015 gives me:

``````main.c(78): warning C4700: uninitialized local variable 'n' used
main.c(81): warning C4700: uninitialized local variable 'array' used
main.c(83): warning C4700: uninitialized local variable 'result' used
``````

`array` and `result` are pointers, but you never actually point them at anything, so they're pointing who knows where and that's why the segfaults. Create some `MATRIX` objects and use those.

could you show (in the code) how to add 'n' matrices?

First thing I'd do is refactor a little bit - make these things separate in your code:

• Creating new `MATRIX` objects
• Deleting them

This will make the problem easier to approach; your code is a bit of a mess right now.

``````int Add(int *values, int numValues)
If you can do that, then all you have to do is change `int` to `MATRIX` and figure out how to add two matrices, not n.