# Prob: Addition 2 matrices using Pointers in C

Page 1 of 1

## 1 Replies - 18908 Views - Last Post: 29 May 2009 - 02:00 AMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'https://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=107566&amp;s=879cf3b2538c97eac601e411db531249&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 her_ron_potter

Reputation: 0
• Posts: 2
• Joined: 17-September 08

# Prob: Addition 2 matrices using Pointers in C

Posted 29 May 2009 - 01:18 AM

I want to write a program to add 2 matrices using pointers. Here is my code:

```#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void main(){

int A[10][10], B[10][10], C[10][10];
int row, col;
int i, j;

int *ptr1[10], *ptr2[10], *ptr3[10];

ptr1[0] = (int*)malloc(10*10*sizeof(int));
ptr2[0] = (int*)malloc(10*10*sizeof(int));
ptr3[0] = (int*)malloc(10*10*sizeof(int));

//Accept the dimension of the matrix
printf("Enter the dimension of the matrix: ");
scanf("%d %d", &row, &col);

//Accept value of matrix A and B
printf("Enter the value of matrix A and B: \n");

for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
printf("\nA[%d, %d], B[%d, %d] : ", i,j,i,j);
scanf("%d %d", &A[i][j], &B[i][j]);
C[i][j] = A[i][j] + B[i][j];
ptr1[i][j] = A[i][j];
ptr2[i][j] = B[i][j];
ptr3[i][j] = C[i][j];

}

}

for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
printf("\nA[%d, %d] = %d, B[%d, %d] = %d, C[%d, %d] = %d\n",i,j,ptr1[i][j],i,j,ptr2[i][j],i,j,ptr3[i][j]);
}
}

free(ptr1);
free(ptr2);
free(ptr3);

getch();

}
```

But when I execute, the program didn't run as I wanted.

It's run normally if the dimension of matrix is: 1 1

but if the dimension is not 1 1 it will show error:

plz help me

Is This A Good Question/Topic? 0

## Replies To: Prob: Addition 2 matrices using Pointers in C

### #2 AmitTheInfinity

• C Surfing ∞

Reputation: 119
• Posts: 1,565
• Joined: 25-January 07

## Re: Prob: Addition 2 matrices using Pointers in C

Posted 29 May 2009 - 02:00 AM

It's because of lines like these...
```ptr1[0] = (int*)malloc(10*10*sizeof(int));

```

you have arrays [ptr1, ptr2, ptr3] of integer pointers with 10 pointer elements in it. But you allocated all 100 integer element memory to first ptr[0] pointer of your pointer array. All other remain dangling!

Now when you access this dynamically created array and try to go for ptr[1][X] it will crash as you don't have any memory allocated to anyone except ptr[0]!

This is one of the ways to allocated 2D array memory dynamically [look at that for loop closely].