I've created a program to calculate Pascal's triangle:
#include <stdio.h>
#include <stdlib.h>
void pascal(int limit)
{
int *begin;
begin=(int*)malloc(2*sizeof(int));
*begin=1;
*(begin+1)=1;
int* p,q,s,t;
int row=2,n=3,x;
p=begin;
q=begin+1;
for(n=3;n<=limit+1;n++)
{
if(n==4)
{
free(begin);
}
x=1;
printf("Row (%d) : ",row);
for(int* i=p;i<=q;i=i+1)
{
printf("%d ",*i);
}
putchar('\n');
s=(int*)malloc(n*sizeof(int));
t=s+n-1;
*s=*p;
*t=*q;
for(int* g=p;g<q;g=g+1)
{
*(s+x)=*g+*(g+1);
x++;
}
p=s;
q=t;
row++;
}
}
int main(void)
{
int i;
printf("Till which row would you like to calculate the Pascal Triangle?\n\n");
printf("Type your answer:\t");
scanf("%d",&i);
putchar('\n');
if(i<n)
printf("Nope, you can't do that\n");
else
{
printf("Row (1) : 1\n");
pascal(i);
}
}
My idea was to work with 2 arrays at the same time, but there is still a problem in my algorithm. How am I supposed to free the memory I allocated before? The first 8 bytes of begin are easy to free, but what should I do so I can free the memory I allocated through the pointers?