c - 可变函数参数的段错误

标签 c variables segmentation-fault arguments

我的程序编译没有错误,但是当我运行它时,在我输入一个值(例如半径)后它因段错误而退出。

我将其构造为采用可变数量的参数,但我怀疑这可能与我在“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/

相关文章:

javascript - 如何在隐藏字段中使用由 javascript 函数创建的变量?

c - 插入排序段错误

c - 现有的线程池 C 实现

c++ - 生成文件行 `test -f `

c - 这个链表程序中每一行的作用是什么?

C++ - 常量变量,这是一个正确的术语吗?

复杂的c代码,我需要任何人来解释它是如何工作的吗?

java - 将随机数的返回值存储为局部变量?

c++ - 在循环中使用 Realloc

Java 1.6 段错误 11 (OSX 10.7.4)