gpt4 book ai didi

连接 C ansi 中的任何内容

转载 作者:行者123 更新时间:2023-11-30 18:31:54 25 4
gpt4 key购买 nike

我需要创建一个 C 函数来连接两个任意类型的数据并返回连接结果的字符串。我在下面实现了这个功能,但是不起作用。有人可以帮助我吗?

// void pointer does not store value, is just the address of a memory location
char* concatenate(void* varA, int tamA, void* varB, int tamB)
{
// char is 1 byte
char* result;
char* a,b; // helpers
result = malloc((tamA+tamB)*sizeof(char));

a = varA; // "a" receives the address pointed to by the pointer varA
b = varB; // "b" receives the address pointed to by the pointer varB
*result = *result << tamA + *a;
*result = *result << tamB + *b;
result = a; // let the results point to "a"
return result; // the result is the pointer "a"
}

最佳答案

在 C 中,这就是你所问的问题,即使你的代码是 C++,你也不能那样做。

无法从裸露的 void * 中找出如何将其转换为字符串。

您必须添加某种形式的类型信息,例如 printf() 的字符串,例如使用%d 表示十进制整数等。

我认为这将是一个可行的原型(prototype):

char * concat_any(const char *format1, const void *data1,
const char *format2, const void *data2);

我并不是说“最佳”甚至“合适”,但至少可以实现该原型(prototype)。 format 字符串可以是 printf() 样式,或其他样式。

请注意,对于 C,这也非常不切实际,因为采用 void * 意味着您始终需要一个指向数据的指针。如果你想例如连接两个数字,你不能这样做:

char *fortytwo = concat_any("%d", 4, "%d", 2);  /* BROKEN CODE */

因为它传递整数而不是void *,这是非常丑陋的。你必须这样做:

const int four = 4, two = 2;
const char *fortytwo = concat_any("%d", &four, "%d", &two);

这显然不太方便。

所以,最好使用可变参数,但是这样你就会遇到无法将不同的可变参数与不同的非变量参数关联起来的问题,如下所示:

char * concat_anyv(const char *format1, ...,
const char *format2, ...); /* BROKEN CODE */

那么,首先有两个格式化字符串,然后信任调用者将这两个参数作为可变参数传递怎么样?这将给出:

char * concat_anyv2(const char *format1, const char *format2, ...);

现在我们正在说话。这可以简单地实现,甚至:在内部连接两个格式化字符串,然后调用 vsnprintf()两次:一次计算缓冲区大小,然后分配,然后再次调用。

用法如下:

char *fortytwo = concat_anyv2("%d", "%d", 4, 2);

完成。

关于连接 C ansi 中的任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18533508/

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