gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:22:28 26 4
gpt4 key购买 nike

我正在尝试编写一个函数,该函数具有可变数量的整数/整数数组参数,该函数将所有元素连接到一个一维数组中。我在两种情况之一中挣扎,其中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);

}

最佳答案

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。这样做毫无意义。

I'm struggling with one of the two scenarios where current_item turns out to be an array instead of just an integer. How can I access the individual elements of this array and assign them to pOutList?



函数参数不能是数组。但是它可以是指向数组元素的指针,我想这就是您的意思。如果是这种情况,那么您可以像这样从varargs中获取指针:
WORD* current_item = va_arg(next_item, WORD*);

然后,可以像使用任何指向元素的指针一样,将元素从数组复制到数组。

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

不过,更笼统地说:我建议您在C++中根本不要使用C风格的变量。用脚拍自己太容易了。可变参数模板是实现相似目标的更安全,更强大的方法。

就是说,我不太了解您要做什么,因此我无法确认使用任何形式的variadics是否有意义。

关于c++ - 使用可变参数函数将整数和/或整数数组转换为单个int数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59516892/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com