当&
添加到y
时,y
永远不会改变,但是如果我删除&
,y
会发生变化,但程序在scanf
后立即结束:
double scan_data(char *a, double *b) {
char x;
double y;
int result;
printf("input en operator og hvis relevant, operand: ");
scanf("%c, %lf", &x, &y);
/* Hvis unær output=0,0. */
printf("scan y step 1: %lf", &y);
unary(x, &result);
if (result == -1) {
y = 0.0;
}
*a = x;
*b = y;
printf("scan b: %d", *b);
return 0;
}
要scanf()
的参数必须是scanf()
存储转换值的地址。如果y
被定义为double
,则必须为需要指向double
的指针的转换%lf
传递&y
(y
的地址)。
对于printf
,您必须为%f
(或忽略l
的%lf
)传递一个double
值。通过&y
是一个错误,只是通过y
.
最终printf
也存在类型不匹配:inprintf("scan b: %d", *b);
%d
需要一个int
值,但*b
具有类型double
。你应该写:
printf("scan b: %fn", *b);
以下是修改后的代码:
double scan_data(char *a, double *b) {
char x;
double y;
int result;
printf("input en operator og hvis relevant, operand: ");
if (scanf("%c, %lf", &x, &y) != 2) {
printf("invalid inputn");
return -1.0;
}
/* Hvis unær output=0,0. */
printf("scan y step 1: %fn", y);
unary(x, &result); // no info on this function?
if (result == -1) {
y = 0.0;
}
*a = x;
*b = y;
printf("scan b: %fn", *b);
return 0.0;
}
printf("scan y step 1: %lf", &y);
调用未定义的行为,因为具有错误类型的数据被传递给printf()
:%lf
期望double
但&y
具有类型double*
。
它应该是
printf("scan y step 1: %f", y);
您应该删除额外的&
。此外,%f
也应该用于打印double
printf()
。(%lf
在C99或更高版本中还不错)
printf("scan b: %d", *b);
还会调用未定义的行为,因为double
会传递到预期int
的位置。
它应该像
printf("scan b: %f", *b);
或
printf("scan b: %d", (int)*b);