我的程序编译没有错误,但是当我运行它时,在输入一个半径等值之后,它会以分段错误退出。带有可变函数参数的分段错误
我已经构建了一个可变数量的参数,但我怀疑它可能与我在“shape_area”函数的操作过程中调用每个参数的方式有关。
任何人都可以帮助解释我在这里做错了吗?
#include <stdio.h>
#include <math.h>
#include <stdarg.h>
double shape_area(double shapetype, ...);
int main(void)
{
int shapetype;
double radius, side, length, width, area;
printf("\n\nPlease enter the type of shape you wish to get the area of:\n");
printf("| 1-Circle | 2-Square | 3-Rectangle |\n");
scanf("%d", &shapetype);
// Circle
if(shapetype == 1)
{
printf("\nPlease enter the radius of your circle: ");
scanf("%lf", &radius);
area = shape_area(shapetype, radius);
}
// Square
else if(shapetype == 2)
{
printf("\nPlease enter the side length of your square: ");
scanf("%lf", &side);
area = shape_area(shapetype, side);
}
// Rectangle
else if(shapetype == 3)
{
printf("\nPlease enter the side length of your square: ");
scanf("%lf", &length);
printf("\nPlease enter the side length of your square: ");
scanf("%lf", &width);
area = shape_area(shapetype, length, width);
}
else
{
printf("\n\nInvalid Input!\n");
return (0);
}
printf("\n\nArea of Shape: %lf\n\n", area);
return (0);
}
double shape_area(double shapetype, ...)
{
va_list args;
double temparea;
double radius;
double side;
double length;
double width;
radius = va_arg (args, double);
side = radius;
length = radius;
width = va_arg (args, double);
if(shapetype == 1)
{
temparea = M_PI*radius*radius;
}
if(shapetype == 2)
{
temparea = side*side;
}
if(shapetype == 3)
{
temparea = length*width;
}
va_end (args);
return temparea;
}
为什么不使用'double shape_area(double shapetype,double radius,double width)' – wimh
您可以提供样本输入吗?我第一次尝试运行它退出通常与一个不正确的答案,但没有segfaults。 – nmichaels
您是否尝试过使用调试器来帮助您找到问题?它非常适合这些场景。 – kaylum