1 Replies - 10349 Views - Last Post: 29 May 2009 - 02:00 AM Rate Topic: -----

#1 her_ron_potter  Icon User is offline

  • New D.I.C Head

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

Prob: Addition 2 matrices using Pointers in C

Post icon  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
Posted Image

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

plz help me :(

Is This A Good Question/Topic? 0
  • +

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

#2 AmitTheInfinity  Icon User is offline

  • C Surfing ∞
  • member icon

Reputation: 117
  • View blog
  • Posts: 1,559
  • 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].

I hope this will help you. :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1