0

When ever the program finds a row in witch the first element's last number and the last element's last number divide by 2, then it should add other row to the matrix. I need to do this using dynamic allocation. Here is the code:

#include <stdio.h>
#include <malloc.h>

int **a;
int cifra(int n){

    int c=0;
    while (n)
    {
        c=n%10;
        n/=10;`
    }
    return c;
 }

 int conditie(int i, int m)
 {
     if(cifra(a[i][0])%2==0 && a[i][m-1]%2==0)
        return 1;
    return 0;`
 }

 int main()
 {
    int i,j,n,m,k,l;
    printf("n=");
    scanf("%d",&n);
    printf("m=");
    scanf("%d",&m);`

    a=(int**)malloc(n*sizeof(int*));
    a[0]=(int*)malloc(n*m*sizeof(int));

    for( i=1;i<n;i++)
        a[i]=a[i-1]+m;

    for(i=0;i<n;i++)
        for(j=0;j<m;j++)
            {
                printf("a[%d][%d]=",i,j);
                scanf("%d",&a[i][j]);
            }
    for(i=0;i<n;i++)
        if(conditie(i,m))
        {
           n++;
           a=(int**)realloc(a,n*sizeof(int*));
           for(k=n-1;k>i;k--)
               for (l=0;l<m;l++)
                    a[k][l] = a[k-1][l]; //the program seems to be crashing here
            for(j=0;j<m;j++)
                a[i+1][j]=-1;
        }
    for(i=0;i<n;i++)
        {
            for(j=0;j<m;j++)
                {
                    printf("%d",a[i][j]);
                }
            printf("\n");
        }
    free(a[0]);
    free(a);
    return 0;
    }
Marcassin
  • 1,386
  • 1
  • 11
  • 21
pxr_64
  • 510
  • 1
  • 8
  • 23
  • 4
    First of all, format your code properly. Second of all, you're obviously going out of bounds somewhere. Some kind soul will probably come along that will debug the whole program for you, but I, for one, don't really enjoy digging through someone else's nested if-thens and finding out why something like `a[k][l]=a[k-1][l]` is breaking... – David Titarenco Nov 28 '13 at 19:47

1 Answers1

2

This is your problem.

for( i=1;i<n;i++)
    a[i]=a[i-1]+m;

You're assigning arbitrary pointers to the a[i]'s and when you deference them it throws a segmentation fault.

randomusername
  • 7,927
  • 23
  • 50