- #1
TheSourceCode
- 14
- 0
Here is the given problem. I have a question for part c and e.
Calculate and print first 12 rows of the famous Pascal triangle, as shown below. Each number is the sum of the two numbers immediately above it. As our intent is to practice pointers, functions, loops, and dynamic memory allocation, the following steps are mandatory (even if you could find an alternative solution):
a. Each row of the triangle is to be referred to via a pointer; thus an array of 12 pointers is to be declared.
b. Cycle over all rows. Use malloc to allocate the necessary amount of memory for each row pointer.
c. Calculate the numbers in the row by summing the respective values from the previous row. All values are to be referred to exclusively via pointers.
d. Write a function that would print a given row in a symmetric fashion as shown below, by
padding the row with the appropriate amount of white space on both sides.
e. In the end, be sure to free all row pointers.
My code works fine but I'm not sure I'm referring to them with pointers (part c). I know arary is the same as *(array+i). Should I be using that notation and if so how do I do this since i have an array of pointers?
My second question is am I using free right? I feel like I should have to free each array but my code doesn't work when I try. Right now this compiles:
I feel like I should be doing this (but it freezes):
Thanks for the feedback!
Calculate and print first 12 rows of the famous Pascal triangle, as shown below. Each number is the sum of the two numbers immediately above it. As our intent is to practice pointers, functions, loops, and dynamic memory allocation, the following steps are mandatory (even if you could find an alternative solution):
a. Each row of the triangle is to be referred to via a pointer; thus an array of 12 pointers is to be declared.
b. Cycle over all rows. Use malloc to allocate the necessary amount of memory for each row pointer.
c. Calculate the numbers in the row by summing the respective values from the previous row. All values are to be referred to exclusively via pointers.
d. Write a function that would print a given row in a symmetric fashion as shown below, by
padding the row with the appropriate amount of white space on both sides.
e. In the end, be sure to free all row pointers.
Code:
#include <stdio.h>
#include <stdlib.h>
#define MAX 12
int main(){
int **triangle;
int i, j;
triangle=malloc(MAX * sizeof(int *));
for (i=0; i<MAX; i++){
triangle[i]=malloc((i+1) * sizeof(int));
triangle[i][0]=1;
triangle[i][i]=1;
for(j=1; j<i; j++)
triangle[i][j]=triangle[i-1][j-1]+triangle[i-1][j];
}
//function to format will go here
free(triangle);
printf("Press enter to continue ...");
getchar();
return 0;
}
My second question is am I using free right? I feel like I should have to free each array but my code doesn't work when I try. Right now this compiles:
Code:
free(array);
Code:
for(i = 0; i < MAX; i++)
free(triangle[i]);
free(triangle);
Last edited: