我们可以两次调用va_start()而不在两者之间调用va_end()吗?

问题描述 投票:0回答:2

这是我的最小示例:

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

void print_strings_and_lengths(int count, ...)
{
    va_list ap;

    /* Print strings */
    va_start(ap, count);
    for (int i = 0; i < count; i++) {
        char *s = va_arg(ap, char *);
        printf("%d - %s\n", i, s);
    }

    /* Print string lengths */
    va_start(ap, count); /* Is it okay to call va_start() again without calling va_end()? */
    for (int i = 0; i < count; i++) {
        char *s = va_arg(ap, char *);
        printf("%d - %zu\n", i, strlen(s));
    }
    va_end(ap);
}

int main()
{
    print_strings_and_lengths(3, "apple", "ball", "cat");
    return 0;
}

此代码在同一变量参数列表上两次调用va_start()。在两次调用之间未调用va_end()函数。此代码定义是否正确,还是会调用未定义的行为?

c variadic-functions
2个回答
0
投票

va_start reference说得最好:


0
投票

C11 7.16.1 / 1:

© www.soinside.com 2019 - 2024. All rights reserved.