user2888532
user2888532

Reputation: 1

Having Trouble Using Pointer in C

i have an assignment asks me to do a Mathematical Models, this is part of my main function, however, when i run it, i always have trouble to scan the number, i just need someone help me to check it. thank you

P.S. if someone enter 3 which is exit this menu, how can i do it? what i think is use exit(), but still doesnt work.

#include <stdio.h>
#include <stdlib.h>

int main(void)

{

    int option =0;

    double *x1, *x2,*y1, *y2, *x,*y;

    double *slope;

display_menu();

scanf(" %d", &option);

    if(option ==1)

{

printf("You choose to do the Two-point form. \n");

printf("Enter the x-y coordinates of the first point separate by a space=> ");

scanf("%lf","%lf", &x1,&y1);

printf("Enter the x-y coordinates of the second point separate by a space=> ");

scanf("%lf","%lf", &x2,&y2);

two_point_form(*x1,*y1,*x2,*y2); /* <<<--------this one is always wrong.  T.T */

 

}
}


int two_point_form(double *x1, double *y1, double *x2, double *y2)

{

    double slope, intecept;

printf("Two-point form: ");

printf(" (%lf-%lf)", *y2,*y1);

printf(" m = --------");

printf(" (%lf-%lf)", *x2-*x1);

slope = (*y2-*y1)/(*x2-*x1);

intecept = *y1-slope**x1;

printf("Slope-intecept form: y= %lfx+%lf", slope, intecept);

}

Upvotes: 0

Views: 83

Answers (3)

zubergu
zubergu

Reputation: 3706

You create double * x1 (pointer to double) which is fine, except you don't initialize it. I also assume that you wanted double x1 because that's what creates variable, first one creates just pointer to a variable of some type.
Then you call scanf() that expects pointer to variable, but instead of giving it a pointer you give it &x1 which is pointer to pointer to double. Next bumpt.
And the last one is *x1 part which dereferences uninitialized pointer to double.

It's a tripple mess, and what you should(probably) do is

double x1,x2...;

scanf("%lf...", &x1...);

two_point_form(&x1,...);

and what you should(definitely) do is grab some C book and read pointers chapter.

Upvotes: 0

Kninnug
Kninnug

Reputation: 8053

You're passing pointer-to-pointer-to-doubles to scanf. And dereferencing x1, y1 to two_point_form et cetera, which gives undefined behaviour, because they were never allocated.

As you're doing with option declare your doubles as 'normal' doubles, not pointers:

double x1, y1, x2, y2, x, y;

Then pass their addresses to scanf and their values to two_point_form:

two_point_form(x1, y1, x2, y2);

Upvotes: 1

Crowman
Crowman

Reputation: 25908

Here:

double *x1, *x2,*y1, *y2, *x,*y;

...

scanf("%lf","%lf", &x1,&y1);

you're setting up pointers, passing the addresses of pointers to scanf(), but trying to read doubles into them. That first line should be:

double x1, x2, y1, y2, x, y;

Upvotes: 0

Related Questions