在C中使用指针时遇到问题

时间:2013-10-17 00:25:10

标签: c pointers

我有一个作业要求我做一个数学模型,这是我的主要功能的一部分,然而,当我运行它时,我总是很难扫描数字,我只需要有人帮我检查它。谢谢

P.S。如果有人输入3退出此菜单,我该怎么办?我认为使用exit(),但仍然无法正常工作。

#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);

}

3 个答案:

答案 0 :(得分:1)

您将指向指针的指针传递给scanf。并解除引用x1y1two_point_form等等,它们提供未定义的行为,因为它们从未被分配过。

当你正在使用option时,将你的双打声称为'普通'双打,而不是指针:

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

然后将他们的地址传递给scanf,将他们的值传递给two_point_form

two_point_form(x1, y1, x2, y2);

答案 1 :(得分:0)

下面:

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

...

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

您正在设置指针,将指针的地址传递给scanf(),但尝试将double读入其中。第一行应该是:

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

答案 2 :(得分:0)

你可以创建double * x1(指向double的指针),除非你没有初始化它。我还假设你想要double x1,因为这是创建变量的东西,第一个只创建指向某个类型的变量的指针。
然后你调用scanf()期望指向变量的指针,而不是给它一个你给它的指针&x1,这是指向double的指针。下一次尝试。
最后一个是*x1部分,它将未初始化的指针取消引用为double。

这是一个混乱,你应该(可能)做的是

double x1,x2...;

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

two_point_form(&x1,...);

你应该做什么(绝对)做的就是获取一些C书并阅读指针章节。

相关问题