使用可变参数函数将整数和/或整数数组转换为单个int数组

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

我正在尝试编写一个函数,该函数具有可变数量的整数/整数数组参数,该函数将所有元素连接到一个一维数组中。我在两种情况之一中挣扎,其中current_item证明是数组而不是整数。如何访问此数组的各个元素并将其分配给pOutList?

typedef unsigned short      WORD;

int PinListJoin(WORD * pOutList, ...) {

    int index=0;
    boolean isArray = false;

    va_list next_item;
    va_start(next_item, pOutList);
    WORD current_item = va_arg(next_item, WORD);
    int current_item_size = sizeof(current_item) / sizeof(WORD);

    if (current_item_size > 1) {
        isArray = true;
        for (int pinidx = 0; pinidx < current_item_size; pinidx++) {
            pOutList[index] = current_item;
            index++;
        }
    }
    else {
        isArray = false;
        pOutList[index] = current_item;
        index++;
    }

    va_end(next_item);

    return(current_item_size);

}
c++ arrays variadic-functions
1个回答
0
投票
boolean isArray = false;

C ++中没有boolean数据类型。

此外,该函数中从未使用isArrayindex变量的值。

typedef unsigned short      WORD;
WORD current_item = va_arg(next_item, WORD);

这行不通。各种各样的争论被提倡。 unsigned short提升为int(通常;在某些外来系统上,可能是unsigned int)。将非促销类型与va_arg一起使用将导致不确定的行为。您可以使用这样的技巧为任何系统获取正确的类型:

using promoted_word = decltype(+WORD(0));
WORD current_item = WORD(va_arg(next_item, promoted_word));
WORD current_item = va_arg(next_item, WORD);
int current_item_size = sizeof(current_item) / sizeof(WORD);

WORD的大小除以WORD的大小始终为1。这样做没有意义。

我正在努力解决两种情况之一,其中current_item证明是数组而不是整数。如何访问此数组的各个元素并将其分配给pOutList?

Function参数不能为数组。但是它可以是指向数组元素的指针,我想这就是您的意思。如果真是这样,那么您可以像这样从varargs中获取指针:

WORD* current_item = va_arg(next_item, WORD*);

但是仍然存在两个问题:1.无法基于该指针找出数组的大小,并且2.无法找出传递了哪种类型的参数。您可以看一下printf的界面,以了解如何解决该问题。使用指定这些类型的格式字符串在那里解决。数组的长度通过使用前哨值(空终止符)来解决。另一种方法是将长度作为单独的参数传递。

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