search

Home  >  Q&A  >  body text

c++ - c语言结构体可以通过等号复制么?

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

struct test
{
    int a[5];
};


void print_test(struct test* a, const char* msg)
{
    int i;
    printf("%s:\t", msg);
    for (i = 0; i < 5; ++i)
        printf("%d ", a->a[i]);
    printf("\n");
}


void reset(struct test* input, int start)
{
    int i;
    struct test tmp;
    for (i = 0; i < 5; ++i)
        tmp.a[i] = start + i;

    *input = tmp;
}

int main()
{
    struct test r1, r2, r3;
    int i;
    for (i = 0; i < 5; ++i) {
        r1.a[i] = i;
        r2.a[i] = i + 20;
        r3.a[i] = i + 40;
    }

    print_test(&r1, "r1");
    print_test(&r2, "r2");
    print_test(&r3, "r3");

    r1 = r2;
    r2 = r3;
    reset(&r3, 80);

    print_test(&r1, "r1");
    print_test(&r2, "r2");
    print_test(&r3, "r3");

    return(0);
}

我以前一直以为结构体复制需要用memcpy这种东西,今天才知道可以直接用=号,求教一下各位。

天蓬老师天蓬老师2803 days ago556

reply all(4)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 12:05:25

    C language

    In C language, the structure is a continuous memory space, and the = assignment operation is used. The bottom layer uses memcpy;
    If there is a pointer variable in the structure; after the operation. The two pointers point to the same area without allocating a new area;

    struct S
    {
    	int a;
    	char * b;
    };
    
    
    int main(){
    
    	S s1;
    	s1.b = new char[5];
    	memcpy(s1.b,"hell",5);
    	
    	S s2;
    	s2 = s1;
    	
    	printf("s1.b:%s ,%d \n s2.b:%s,%d\n" ,s1.b,int(s1.b),s2.b,int(s2.b));
        return 0;
    }
    
    output://复制后的地址空间相同
    s1.b:hell ,4921176
    s2.b:hell,4921176

    C++

    In C++, struct and class have the same function. They are both used to define classes. The only difference is that the default access permission in the structure is public, while the class definition is private;
    When defining a class, the c++ compiler A default constructor, copy constructor, and assignment operation function operator=
    will be automatically added to each class. When operating through the = sign,

    a = b;

    Both:

    a.operator=(b);
    

    The implementation details within the operator=() function are: for basic types, copy directly; for custom types, call the copy constructor to copy;

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 12:05:25

    The structure is not a pointer, so it can be assigned directly, but the array is a pointer, so no, that’s what I think

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 12:05:25

    The structure is composed of lumps. When assigning values, the whole lump is assigned (the bottom layer is also memcoy)

    reply
    0
  • 巴扎黑

    巴扎黑2017-04-17 12:05:25

    If you use equal directly, it consumes too much memory. Structure pointers are better.

    reply
    0
  • Cancelreply