使用以一个内部结构的地址作为参数的函数将一个内部结构的变量复制到另一个内部结构 [英] Copying variables of one inner struct to other inner struct using a function that takes address of one inner struct as a parameter
本文介绍了使用以一个内部结构的地址作为参数的函数将一个内部结构的变量复制到另一个内部结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个看起来像这样的复杂结构.
I have a complex structure which looks like this.
struct a
{
struct b
{
int b_inner_int;
char b_inner_char;
}x;
struct c
{
int c_inner_int;
char c_inner_char;
}y;
}z;
我使用一个函数,它将struct c"的地址作为参数.现在我希望这个函数将struct c"的值复制到struct b".我在主函数中进行的函数调用可能如下所示.
I use a function, that takes address of "struct c" as an argument. Now I want this function to copy the values of "struct c" to "struct b". The function call that I make in the main function may look like this.
copy_val(&z.y);
现在,我如何定义 copy_val?有什么建议?如果我定义了一个 struct c 类型的指针,如下所示,它不起作用.
Now, how do I define copy_val? Any suggestions? If i define a pointer of type struct c, like below it isn't working.
void copy_val(struct c *addr)
{
struct c *tmp=addr;
int tmp_int=tmp->c_inner_int;
int tmp_char=tmp->c_inner_char;
tmp=tmp-1; /** assuming that b and c are of same type and decrementing pointer by 1 takes to beginning of b **/
tmp->b_inner_int=tmp_int;
tmp->b_inner_char=tmp_char;
}
推荐答案
#include <stdio.h>
#include <stddef.h>
struct a
{
struct b
{
int b_inner_int;
char b_inner_char;
}x;
struct c
{
int c_inner_int;
char c_inner_char;
}y;
}z;
void copy_val(struct c *addr){
size_t offset_c = offsetof(struct a, y);
size_t offset_b = offsetof(struct a, x);
struct b *bp = (struct b*)((char*)addr - offset_c + offset_b);
bp->b_inner_int = addr->c_inner_int;
bp->b_inner_char = addr->c_inner_char;
}
int main(void){
z.y.c_inner_int = 1;
z.y.c_inner_char = '1';
copy_val(&z.y);
printf("%d, %c\n", z.x.b_inner_int, z.x.b_inner_char);
return 0;
}
这篇关于使用以一个内部结构的地址作为参数的函数将一个内部结构的变量复制到另一个内部结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文