gpt4 book ai didi

C语言 : How to pass a variable arguments list of void* to a function

转载 作者:太空宇宙 更新时间:2023-11-04 08:01:42 24 4
gpt4 key购买 nike

我正在尝试将 void* 元素的可变参数列表传递给 C 中的函数。

  1. 我该怎么做?

  2. 如何计算列表中的项目数?

  3. 如何遍历可变参数列表并传递每个 void* 项到另一个以 void* 项作为参数的函数?

这就是我所做的,但它不起作用。

 void AddValues(List* data, void* args, ...) {

int len = sizeof (args) / sizeof (*args);


for(int i=0;i<len;i++){ processItem(args[0]); }

}

void processItem(void* item){

}

最佳答案

How do I calculate the number of items in the list?

你不能。它必须是提供的或可派生的。

How do I loop through the var-args list and pass each void item to another function that takes a void* item as its parameter?*

Variadic Functions 中所述,

#include <stdarg.h>

void AddValues(int count, ...) {
va_list args;
va_start(args, count);

for(int i=count; i--; )
processItem(va_arg(args, void*));

va_end(args);
}

示例用法:

void* p1 = ...;
void* p2 = ...;
void* p3 = ...;
void* p4 = ...;

AddValues(4, p1, p2, p3, p4);

这取决于你在做什么,但你可能应该使用数组而不是可变参数。

void AddValues(int count, const void** args) {
for(int i=count; i--; )
processItem(*(args++));
}

示例用法:

#define C_ARRAY_LENGTH(a) (sizeof(a)/sizeof((a)[0]))

void* ptrs[4];
ptrs[0] = ...;
ptrs[1] = ...;
ptrs[2] = ...;
ptrs[3] = ...;

AddValues(C_ARRAY_LEN(ptrs), ptrs);

或者(如果指针不能为 NULL):

void AddValues(const void** args) {
while (*args != NULL)
processItem(*(args++));
}

示例用法:

void* ptrs[5];
ptrs[0] = ...;
ptrs[1] = ...;
ptrs[2] = ...;
ptrs[3] = ...;
ptrs[4] = NULL;

AddValues(ptrs);

关于C语言 : How to pass a variable arguments list of void* to a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46165543/

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