Jesucristo
Jesucristo

Reputation: 31

create Pascal triangle in c

I try to make a pascal triangle of n rows and I have to make a fucntion for allocate memory for the matrix, a function to print and free memory I think I have a lot of trouble in my code in the function build I try to allocate the memory for the matrix and charge it i use a function full for chage the matrix, I think my principal problem is that I have an irregular matrix I don't know how to procede, maybe make an array of arrays or somthing like that could be better, sorry for my english

int main()
{
    int **triangle=NULL;
    int n;
    printf("size of triangle");
    scanf("%d",&n);
    build(&triangle,n);
    print(triangle,n);
    return 0;
}
void build(int***triangle,int n){
    *triangle=(int**)calloc(n,sizeof(int*));
    int i;
    for(i=0;i<n;i++){
        *(triangle)[i]=(int*)calloc(i+1,sizeof(int));
    }
    full(*triangle,n);
}
void full(int**triangle,int n){
    int i;
    int j;
    for(i=0;i<n;i++){
        for(j=0;j<i;j++){

            if(j==0){
                triangle[i][j]=1;
            }
            else
            if(j==i){
                triangle[i][j]=1;
            }
            else
            triangle[i][j]=triangle[i-1][j-1]+triangle[i-1][j];

            }
        }
    }

void print(int **triangle,int n){
    int i;
    int j;
    for(i=0;i<n;i++){
        for(j=0;j<i;j++){
            printf("%d",triangle[i][j]);
        }
    }
}

Upvotes: 1

Views: 326

Answers (1)

Jesucristo
Jesucristo

Reputation: 31

*(triangle)[i]=(int*)calloc(i+1,sizeof(int));

should be

(* triangle)[i]=(int*)calloc(i+1,sizeof(int));

Upvotes: 1

Related Questions