开发者

varargs function crashing

开发者 https://www.devze.com 2023-01-11 00:28 出处:网络
I have a function that is supposed to take a variable number of arguments (using varargs) based on a format string:

I have a function that is supposed to take a variable number of arguments (using varargs) based on a format string:

void va(const char* name, const char* argformat, ...) {
    int numOfArgs = strlen(argformat);

    std::string buf = "asdf";

    va_list listPointer;
    va_start(listPointer, numOfArgs);
    char* blah;

    for(in开发者_如何学编程t i = 0; i < numOfArgs; i++) {
            switch (argformat[i]) {
                    case 's':
                            cout << va_arg(listPointer, char*) << endl;
                            break;
                    case 'i':
                            cout << va_arg(listPointer, int) << endl;
                            break;
                    case 'f':
                            cout << va_arg(listPointer, float) << endl;
                            break;
                    case 'b':
                            cout << va_arg(listPointer, bool) << endl;
                            break;
                    default:
                            break;
            }
    }

    va_end(listPointer);

    return;
}


int main() {
    va("fe", "sb", "asdf", true);

    return 0;
}

It crashes.

If I change

cout << va_arg(listPointer, char*) << endl;

to

cout << va_arg(listPointer, char) << end;

it prints "a".

What am I doing wrong?


It should be va_start(listPointer, argformat). va_start takes the last named parameter as its second argument. (Which technically means that you don't need to pre-calculate the length of the argument string at all — just iterate over the characters (iterating over the varargs as you go) until you get to the end of the string.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号