please tell me what's wrong with it?
From my perspective, in the big picture, what's wrong with it is that you copy the contents of array b
into array a
on every iteration:
for (j = 0; j <= i; j++) {
a[j] = b[j];
}
This is exactly the sort of needless memory shuffling that pointers allow us to avoid! So let's address that problem, and while we're at it, fix all the other little bugs in the code:
void pascal(int n) {
int a[100], b[100]; // size appropriately or allocate dynamically
int *a_ptr = a, *b_ptr = b;
for (int i = 0; i < n; i++) {
b_ptr[0] = b_ptr[i] = 1; // initialize both ends
printf("%d ", b_ptr[0]); // print the left end
for (int j = 1; j < i; j++) { // compute & print the middle
b_ptr[j] = a_ptr[j] + a_ptr[j - 1];
printf("%d ", b_ptr[j]);
}
if (i > 0) { // print the right end if it's not also the left end
printf("%d", b_ptr[i]);
}
printf("\n");
int *temporary = a_ptr; // swap a_ptr and b_ptr
a_ptr = b_ptr;
b_ptr = temporary;
}
}