简体   繁体   中英

Segmentation Fault 11 when adding two 2D arrays using structs

I have been working on a program that does math on matrices, and decided to create a struct containing the information required to do the calculations:

In matrices.h:

 struct Matrix{
  int x; //x
  int y; //y
  int **matrix; //hold matrix values
 };

I can print out the values of a matrix using the output command:

void output(struct Matrix* matris){
int c,d;
for (c=0;c<matris->x;c++){
    for(d=0;d<matris->y;d++){
        printf(" %d ",matris->matrix[c][d]);
    }
    printf("\n");
}
printf("\n Press any key to continue...");
scanf("%d",&c);
}

This function however, fails with segmentation fault 11, where the addition takes place.

 void doAddition(struct Matrix* moutput, struct Matrix* matrixa, struct Matrix* matrixb){
  int c,d;
  for(c=0;c<matrixa->x;c++){
    for(d=0;c<matrixa->y;d++){
        moutput->matrix[c][d] = (int)matrixa->matrix[c][d] + (int)matrixb->matrix[c][d];
    }
  }
}

Any help would be greatly appreciated.

Edit:

Error log:

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000100200000
0x0000000100001392 in doAddition (moutput=0x7fff5fbff800, matrixa=0x7fff5fbff820, matrixb=0x7fff5fbff810) at matrices.c:109
109 moutput->matrix[c][d] = (int)matrixa->matrix[c][d] + (int)matrixb->matrix[c][d];

There is typo:

This line in doAddition()

for(d = 0; c < matrixa->y; d++){

shall be

for(d = 0; d < matrixa->y; d++){

Hint : Allow youself more "spaces", this enhances readability and with this reduces the risk of misreadings.

Hint^2 : Learn how to use a debugger (for example gdb ), and use it. It'd have given you the possiblitly to inspect the variable's values around the line the program crashed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM