0

I created a simple function that creates a dynamic 2D array with variable sized rows to store pascals triangles.The number of rows of the pascal triangle is passed as an argument.The code works fine when i try to print the resultant 2D array inside the function.However the created array is not accessible outside the function.

The function:

int ** solve(int A, int *len1, int *len2) 
{
    int **b=(int **)malloc(A * sizeof(int *));
    int i,j;
    *len1=A;
    len2=(int*)malloc(A*sizeof(int));

    for(i=0;i<A;i++)
    {
        len2[i]=i+1;
        b[i]=(int *)malloc((i+1)* sizeof(int));
        if(i==0)
        {
            b[i][0]=1;
        }
        else
        {
            for(j=1;j<len2[i-1];j++)
            {
                b[i][j]=b[i-1][j]+b[i-1][j-1];
            }

            b[i][0]=b[i-1][0];
            b[i][i]=b[i-1][j-1]; 
        }
    }

    return b;
}

The driver code used to test the same

int main()
{
    int **x;
    int len1,*len2,i,j;

     x=generate(5,&len1,len2);
    for(i=0;i<len1;i++)
    {
      for(j=0;j<len2[i];j++)
        printf("%d  ",x[i][j]);
      printf("\n");
    }

    return 0;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • [dont cast malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Barmar Apr 10 '20 at 20:30
  • You need to change the function to `generate(int A, int *len1, int **len2);` and call it with `generate(5, &len1, &len2);` – Barmar Apr 10 '20 at 20:35

0 Answers0