简体   繁体   English

将混合类型的结构转移到不同存储位置中的相同结构

[英]Transferring struct of mixed types to same struct in different memory location

I'm trying to make a small routine that will allow me to make two copies of a struct via pointers and transferring data from one struct to the other only if the other struct contains no data at that point. 我正在尝试制作一个小的例程,该例程将允许我通过指针制作一个结构的两个副本,并且仅当另一个结构此时不包含任何数据时才将数据从一个结构传输到另一个结构。 I am successful with copying the first string over (struct member a) and the second struct member is ok, but the third and fourth are incorrect. 我成功复制了第一个字符串(结构成员a),第二个结构成员正常,但是第三个和第四个不正确。

#include "stdio.h"
#include "string.h"

struct A{
    char a[4];
    long b;
    unsigned long c;
    char d;
};

int main(){
    char mb[600];
    struct A *m1=(struct A*)mb;
    char *p=(char*)m1;
    struct A *m2=(struct A*)(mb+100);
    char *pp=(char*)m2;
    memcpy(m1->a,"123",4);
    m1->b=-123;
    m1->c=123;
    m1->d='X';
    m2->b=-456;
    unsigned long q=sizeof(m2);
    while (q-- > 0){
        if (*pp=='\0'){*pp=*p;}
        pp++;p++;
    }
    printf("A=%s B=%ld C=%ld D=%c\n",m2->a,m2->b,m2->c,m2->d);
}

Compilation of the code works fine. 代码的编译工作正常。 When I do run it, I see these results: 当我运行它时,我看到以下结果:

A=123 B=-456 C=0 D=

What I'm expecting instead is: 我期望的是:

A=123 B=-456 C=123 D=X

I don't want to rewrite the code so that I individually check the value of each member for data. 我不想重写代码,以便我逐一检查每个成员的值以获取数据。 The struct I will work with will be much larger later on and checking each member using strcmp or direct comparison will take up alot of lines of code. 我将使用的结构稍后会更大,使用strcmp或直接比较检查每个成员将占用很多代码行。 I'm looking for something more compact. 我正在寻找更紧凑的东西。

What can I do to fix this? 我该怎么做才能解决此问题?

UPDATE: 更新:

I changed my code and now tried using this while loop instead of the one above: 我更改了代码,现在尝试使用while循环代替上面的代码:

    while (q-- > 0){
if (pp[q]=='\0'){pp[q]=p[q];}
}

and the results are still the same (not what I want). 结果仍然是相同的(不是我想要的)。

First off, you're relying on mb being initialized to all zeros, which seems to have happened incidentally when you ran it, but is not guaranteed. 首先,您需要将mb初始化为全零,这似乎是在您运行它时偶然发生的,但不能保证。 If you want it to be initialized to all zeros (and it looks like you do), do that explicitly: 如果您希望将其初始化为全零(看起来像您这样做),请明确地执行以下操作:

memset(mb, 0, sizeof(mb));

That said, your problem is that you're only copying sizeof(m2) bytes. 就是说,您的问题是您只复制sizeof(m2)个字节。 m2 is a pointer, so sizeof(m2) is the size of a pointer, not the size of struct A . m2是一个指针,所以sizeof(m2)是指针的大小, 而不是 struct A的大小。 You probably want sizeof(*m2) instead. 您可能需要使用sizeof(*m2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM