gpt4 book ai didi

将 void 指针复制到另一个 void 指针?

转载 作者:行者123 更新时间:2023-11-30 18:44:58 24 4
gpt4 key购买 nike

我正在尝试将 void 指针复制到另一个指针数组的不同索引,字符工作正常,但整数和 double 出现问题

这是我的结构:

typedef struct vector_struct {
size_t e_sz;
char e_type;

#define V_INT 1
#define V_DOUBLE 2
#define V_CHAR 3

unsigned no_e;
unsigned cur_cap;
void* e_array;

}* vector_type;
//for typecasting
#define vector_int_at(v,i) (*((int*)v_at(v,i)))
#define vector_double_at(v,i) (*((double*)v_at(v,i)))
#define vector_char_at(v,i) (*((char*)v_at(v,i)))

void* v_at(vector_type v, iterator i) {
if ( v == NULL )
fail("v_at() Error: no such vector");
if ( i == iterator_end )
i = v->no_e -1;
if ( i < 0 || i >= v->no_e )
fail("v_at() Error: no such element in this vector");
return (v->e_array+i); //return element
}

我想将值复制到 void* e_array 中,它可以是整数、字符或 double 值。

void v_push_back(vector_type v, void* new_val){
if ( v->no_e >= v->cur_cap ) {
/*** need to expand the array ***/
v->cur_cap += (v->cur_cap)? v->cur_cap : 2;

v->e_array = check_a(realloc(v->e_array, sizeof(void*) * v->cur_cap));
//allocate memory

}
/*** copy new_val into the array at end position (v->no_e) ***/
printf("%d %d %p\n",v->e_sz,v->no_e,v->e_array+(v->no_e *v->e_sz));
memcpy(
v->e_array +(v->no_e)*v->e_sz,
new_val,
v->e_sz
);

(v->no_e)++;
}

我这样调用这个函数:

c1 = 'o'; v_push_back(vc1,(void*)&c1); //for character
for ( i1 = 0 ; i1 < 10 ; i1++ ){ //for integer
v_push_back(vi1,(void*)&i1);
}

//I call these like
for ( i1 = 0 ; i1 < vector_size(vi1) ; i1++ )
printf(" %ld",vector_int_at(vi1,i1));
printf("\n");

但似乎对于整数不起作用,但对于字符则效果很好,但对于整数,垃圾值会被复制,如下所示: enter image description here

请帮帮我。谢谢

这里是完整的项目: https://s3.amazonaws.com/assignment.pointers.vectorc.implementation/C-VectorImplementation1.zip

最佳答案

我发现了一些问题,

  1. 为了获取当前 vector 类型的第 i 个位置,您需要将 iv->e_sz 相乘。

    void* v_at(vector_type v, iterator i)
    {
    .....
    return ((char*)v->e_array+i*v->e_sz); //return element
    }
  2. 您正在分配您想要的 sizeof(void *)

     v->e_array = check_a(realloc(v->e_array, v->e_sz * v->cur_cap));
  3. 此外,到目前为止,您将地址存储为 int,但您需要存储其值。

    void v_push_back(vector_type v, void* new_val){
    if(v->e_type==V_INT){
    // (v->e_array+(v->no_e))=new_val;
    ((int*)v->e_array)[v->no_e]=*(int*)new_val;
    ^------storing its content
    }
    }

    没有任何类型检查,简单的 memcpy 应该可以工作。

    void v_push_back(vector_type v, void* new_val){
    ....
    memcpy(
    v->e_array +(v->no_e)*v->e_sz,
    new_val,
    v->e_sz
    );
    // *(char*)(v->e_array+v->no_e)=*(char*)new_val;

    (v->no_e)++;
    }

关于将 void 指针复制到另一个 void 指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56059755/

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