IT박스

C에서 한 구조체를 다른 구조체에 할당

itboxs 2020. 6. 27. 11:47
반응형

C에서 한 구조체를 다른 구조체에 할당


다음과 같이 구조체의 한 인스턴스를 다른 인스턴스에 할당 할 수 있습니까?

struct Test t1;
struct Test t2;
t2 = t1;

나는 그것이 간단한 구조에서 작동하는 것을 보았습니다 .bu는 복잡한 구조에서 작동합니까?
컴파일러는 유형에 따라 데이터 항목을 복사하는 방법 (예 : int및 문자열 구분)을 어떻게 알 수 있습니까?


구조가 동일한 유형이면 예입니다. 메모리 사본으로 생각하십시오.


예, 구조체에 할당이 지원됩니다. 그러나 문제가 있습니다.

struct S {
   char * p;
};

struct S s1, s2;
s1.p = malloc(100);
s2 = s1;

이제 두 구조체의 포인터가 동일한 메모리 블록을 가리 킵니다. 컴파일러는 지정된 메모리를 복사하지 않습니다. 어떤 구조체 인스턴스가 데이터를 소유하는지 알기가 어렵습니다. 이것이 C ++이 사용자 정의 가능한 할당 연산자 개념을 발명 한 이유입니다.이 경우를 처리하기 위해 특정 코드를 작성할 수 있습니다.


먼저이 예제를보십시오.

간단한 C 프로그램의 C 코드는 다음과 같습니다.

struct Foo {
    char a;
    int b;
    double c;
    } foo1,foo2;

void foo_assign(void)
{
    foo1 = foo2;
}
int main(/*char *argv[],int argc*/)
{
    foo_assign();
return 0;
}

foo_assign ()에 해당하는 ASM 코드는 다음과 같습니다.

00401050 <_foo_assign>:
  401050:   55                      push   %ebp
  401051:   89 e5                   mov    %esp,%ebp
  401053:   a1 20 20 40 00          mov    0x402020,%eax
  401058:   a3 30 20 40 00          mov    %eax,0x402030
  40105d:   a1 24 20 40 00          mov    0x402024,%eax
  401062:   a3 34 20 40 00          mov    %eax,0x402034
  401067:   a1 28 20 40 00          mov    0x402028,%eax
  40106c:   a3 38 20 40 00          mov    %eax,0x402038
  401071:   a1 2c 20 40 00          mov    0x40202c,%eax
  401076:   a3 3c 20 40 00          mov    %eax,0x40203c
  40107b:   5d                      pop    %ebp
  40107c:   c3                      ret    

할당이 어셈블리의 "mov"명령어로 대체 된 것을 볼 수 있듯이 할당 연산자는 단순히 한 메모리 위치에서 다른 메모리 위치로 데이터를 이동하는 것을 의미합니다. 할당은 구조의 즉각적인 멤버에 대해서만 수행되며 구조에 복잡한 데이터 유형이있는 경우 복사에 실패합니다. 여기서 COMPLEX는 목록을 가리키는 포인터 배열을 가질 수 없음을 의미합니다.

구조 내 문자 배열은 대부분의 컴파일러에서 작동하지 않습니다. 할당은 데이터 유형을 복잡한 유형으로 보지 않고도 복사를 시도하기 때문입니다.


This is a simple copy, just like you would do with memcpy() (indeed, some compilers actually produce a call to memcpy() for that code). There is no "string" in C, only pointers to a bunch a chars. If your source structure contains such a pointer, then the pointer gets copied, not the chars themselves.


Did you mean "Complex" as in complex number with real and imaginary parts? This seems unlikely, so if not you'd have to give an example since "complex" means nothing specific in terms of the C language.

You will get a direct memory copy of the structure; whether that is what you want depends on the structure. For example if the structure contains a pointer, both copies will point to the same data. This may or may not be what you want; that is down to your program design.

To perform a 'smart' copy (or a 'deep' copy), you will need to implement a function to perform the copy. This can be very difficult to achieve if the structure itself contains pointers and structures that also contain pointers, and perhaps pointers to such structures (perhaps that's what you mean by "complex"), and it is hard to maintain. The simple solution is to use C++ and implement copy constructors and assignment operators for each structure or class, then each one becomes responsible for its own copy semantics, you can use assignment syntax, and it is more easily maintained.

참고URL : https://stackoverflow.com/questions/2302351/assign-one-struct-to-another-in-c

반응형