2

不定の引数を処理する方法を学ぶために、Cで簡単な加算計算機を作成しようとしています。以下は正しくコンパイルされますが、出力は常に正しくなく、デバッグするのに十分な知識がありません。どんなポインタも素晴らしいでしょう。

#include <stdio.h>
#include <stdarg.h>

int calculateTotal(int n, ...)
{

    //declartion of a datatype that would hold all arguments
    va_list arguments;

    //starts iteration of arguments
    va_start (arguments, n);

    //declarion of initialization for 'for loop'
    //declation of accumulator
    int i = 0;
    int localTotal = 0;

    for(i; i < n; i++)
    {
        //va_arg allows access to an individual argument
        int currentArgument = va_arg(arguments, int);
        localTotal += currentArgument;
    }

    //freeing the declaration of the datatype that holds the information
    va_end(arguments);

    return localTotal;
}

int main()
{
    int total = calculateTotal(56,7,8);
    printf("Total > %d\n",total);

    return 0;
}
4

1 に答える 1

3

2ではなく最初の引数として56を渡します。次に、関数は56を引数の数として解釈し、初期化された領域を超えてその「パラメーター」を読み取り続けます。

呼び出しをパス2に変更すると、関数から返される結果は15になります。

于 2012-07-02T00:06:23.200 に答える