With compiler warnings on, the problem is clear.
$ make
cc -Wall -g test.c -o test
test.c:9:20: warning: format specifies type 'double *' but the argument has type 'double' [-Wformat]
scanf("%lf", *(coeff+1));
~~~ ^~~~~~~~~~
1 warning generated.
scanf
wants a double pointer, but it's being fed a double value.
What you're trying to do is increment coeff
through the loop to simulate coeff[p]
. What *(coeff+1)
is actually doing is getting the value pointed at by coeff
and adding 1 to it. This is similar to coeff[0] + 1
. scanf
treats this number (which will be gibberish) as a memory address and the program crashes.
What you want is to increment the pointer itself. But not by 1, coeff + 1
is similar to coeff[1]
. Instead use p
: coeff + p
.
You also have the same off-by-one error twice. Your for loops are only iterating 7 times.
for(i = 0; i < 7; i++) {
^
That will go from 0 to 6. An easy rule of thumb is if you want to iterate N times you put i < N
. This works because arrays are 0 indexed.
As far as how get_poly
is designed, here's little reason to require that the user passes in an already allocated pointer. This requires the user to do extra work, and to know how many elements get_poly
will read. If get_poly
wants to read more, all the code calling it will break.
Instead, have get_poly
do the allocation. Then you can also use the argument to ask how many numbers it should read. This makes the function safer and more flexible.
As a final touch, I've consistently used i
for the for loop iterator. It's a standard convention, using p
(for polynomial?) obscures that it's just a loop iterator (and it's not even counting polynomials).
#include <stdio.h>
#include <stdlib.h>
double *get_poly(int num_coeffs){
int i;
double *coeffs = calloc(num_coeffs, sizeof(double*));
printf("Enter the %d coefficients: ", num_coeffs);
for(i = 0; i < num_coeffs; i++){
scanf("%lf", coeffs + i);
}
return coeffs;
}
int main(void){
int i;
double *coeffs = get_poly(8);
printf("output: ");
for(i = 0; i < 8; i++){
printf("%lf ",coeffs[i]);
}
printf("\n");
return 0;
}
And you should avoid scanf
and instead use fgets
+ sscanf
for all the reasons outlined here. I leave that as an exercise.