我的程序编译没有错误,但是当我运行它时,在我输入一个值(例如半径)后它因段错误而退出。
我将其构造为采用可变数量的参数,但我怀疑这可能与我在“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;
}
最佳答案
您需要使用 va_start 初始化参数列表
double shape_area(double shapetype, ...)
{
va_list args;
va_start(args,shapetype);
.
.
关于c - 可变函数参数的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30111180/