c++ - 可变参数列表程序行为异常 - cstdarg

标签 c++ c arguments

这个程序只给出一次正确的结果。我一直在尝试了解如何使用 cstadarg 中的宏来创建和调用具有可变数量参数的函数。

#include <iostream>
#include <cstdarg>
using std::cout;
using std::endl;

int sum(int count, ...)
{

    if(count <= 0)
    return 0;

    va_list myarg_ptr; //create pointer to argument list
    va_start(myarg_ptr, count); // initate pointer to argument list

    int sum(0);

    for(int i=0; i<count; i++)
        sum += va_arg(myarg_ptr, int); // use and increment pointer to arugment list

    va_end(myarg_ptr); // set argument list pointer to NULL 
    return sum;
}


int main(int argc, char* argv[])
{
    cout << sum(9, 11, 22, 33, 44, 55, 66, 77, 6) << endl;
    cout << sum(6, 2, 4, 6, 8, 10, 5) << endl;
    cout << sum(9, 1, 2) << endl;

    std::system("pause");
    return 0;
}

我得到的输出是:

273156986
35
-173256537
Press any key to continue...

最佳答案

修复你的 sum() 调用,求和的元素数量应该是 sum() 的第一个参数

所以,

cout << sum(8, 11, 22, 33, 44, 55, 66, 77, 6) << endl; //8 arguments
cout << sum(6, 2, 4, 6, 8, 10, 5) << endl; // 6 arguments
cout << sum(2, 1, 2) << endl; //2 arguments

关于c++ - 可变参数列表程序行为异常 - cstdarg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17884709/

相关文章:

c++ - 引用结构中的C++内存管理

c - C中如何释放变量占用的内存?

c - 多维数组和指针寻址

c# - 将数组从 vba 传递到 c# 时,数据类型不匹配在哪里?

c++ - 继承和指向 protected 成员的指针

c++ - 在 C++ 中使用原子 TestAndSet 混合无锁和全锁线程同步

c++ - 您如何跟踪每个功能提供的异常安全保证

c - 结构中的结构?

忽略函数中的 C++ 类型检查(需要 double,提供 int)

Powershell 和 logparser 参数