#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2013
    Posts
    1
    Rep Power
    0

    Matrix addition using pointers and DMA


    Hi friends
    I have typed the following code for matrix addition:

    Code:
    #include<stdio.h>
    #include<malloc.h>
    main()
    {
     int r,c,i,j,**a,**b,**s;
     printf("Enter the no of rows and columns of the matrices");
     scanf("%d%d",&r,&c);
     a=malloc(r*sizeof(int));
     a[i]=malloc(c*sizeof(int));
     printf("Enter A elements:\n");
     for(i=0;i<r;i++)
     {
      for(j=0;i<c;j++)
      {
       scanf("%d",&a[i][j]);
      }
     }
     b=malloc(r*sizeof(int));
     b[i]=malloc(c*sizeof(int));
     printf("Enter B elements:\n");
     for(i=0;i<r;i++)
     {
      for(j=0;i<c;j++)
      {
       scanf("%d",&b[i][j]);
      }
     }
     s=malloc(r*sizeof(int));
     s[i]=malloc(c*sizeof(int));
     printf("Addition of the given matrices is:\n");
     for(i=0;i<r;i++)
     {
      for(j=0;i<c;j++)
      {
       *(*(s+i)+j)=*(*(a+i)+j)+*(*(b+i)+j);
       printf("%d",*(*(s+i)+j));
       printf("\t");
      }
      printf("\n");
     }
    When i compile the above code there is no error but if I execute the code I get the following output:

    Enter the no of rows and columns of the matrices2 2
    Segmentation fault (core dumped)

    what's wrong in my code????
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jan 2013
    Posts
    159
    Rep Power
    19
    I get the following warning when I compile your code:

    main.c||In function ‘main’:|
    main.c|9|warning: ‘i’ is used uninitialized in this function [-Wuninitialized]|
    Line 9 is this line:
    Code:
    a[i]=malloc(c*sizeof(int));
    At this point you haven't initialized i. However this statement should probably be in a loop so you allocate memory for each row of your array. Your doing this for each of your matrix variables.

    You're also not allocating memory properly for the columns. You may want to review your documentation for dynamic memory allocation.


    Jim

IMN logo majestic logo threadwatch logo seochat tools logo