gpt4 book ai didi

我可以将变量转换为在 C 中执行期间决定的类型吗

转载 作者:行者123 更新时间:2023-12-05 04:23:45 24 4
gpt4 key购买 nike

int* push_back_int(intVector* target, int push)
{
target->length++;
target->val = (int *)realloc(target->val, target->length * sizeof(int));
target->val[target->length - 1] = push;
return &target->val[target->length - 1];
}
float* push_back_float(floatVector* target, float push)
{
target->length++;
target->val = (float *)realloc(target->val, target->length * sizeof(float));
target->val[target->length - 1] = push;
return &target->val[target->length - 1];
}

有什么方法可以让我保存一个变量来替换转换为 int* 或 float*,这样我就可以使用 void* 为多个变量类型重用相同的代码

最佳答案

没有。在 C 中,该类型仅在编译时可用。

您可以使用void * 来回传递数据,但您需要保留元素大小。这种方法被称为非类型安全(编译器不会捕获错误的“类型”,例如,在下面切换 iq 和 fq,当你弄错时,它会在运行时爆炸最令人印象深刻)。请注意调用代码如何处理转换。

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

struct queue {
size_t push_length;
void *val;
size_t length;
};

void *push_back(struct queue *target, void *push) {
size_t offset = target->length * target->push_length;
target->length++;
void *tmp = realloc(target->val, target->length * target->push_length);
if(!tmp) {
// error handling
return NULL;
}
target->val = tmp;
return memcpy((char *) target->val + offset, push, target->push_length);
}

int main() {
struct queue fq = { sizeof(float), NULL, 0 };
push_back(&fq, &(float) { 2.718 });
push_back(&fq, &(float) { 3.142 });
for(unsigned i = 0; i < fq.length; i++) {
printf("%u: %f\n", i, ((float *) fq.val)[i]);
}

struct queue iq = { sizeof(int), NULL, 0 };
push_back(&iq, &(int) { 1 });
push_back(&iq, &(int) { 2 });
for(unsigned i = 0; i < iq.length; i++) {
printf("%u: %d\n", i, ((int *) iq.val)[i]);
}
}

和输出:

0: 2.718000
1: 3.142000
0: 1
1: 2

您的平台可能需要对 val 的每个元素进行特定对齐(即对于类型 T push_length = sizeof(T) % alignof(T) ? (sizeof(T)/alignof(T) + 1)* alignof( T) : 大小(T)).

关于我可以将变量转换为在 C 中执行期间决定的类型吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73656757/

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