이것저것

C에서 struct를 return하면 어떻게 될까?

ForceCore 2008. 11. 12. 00:41
포인터만 return될까?
그렇진 않고 memory copy가 일어나는 듯!!

#include <stdio.h>

typedef struct X_ {
    int a;
    int b;
    struct X_* next;
} X;

X returnStruct()
{
    X y;
    y.a = 0;
    y.b = 2;
    y.next = NULL;
    printf( "y.b: %d\n", y.b );
    printf( "address of y: %x\n", &y );
    printf( "address of y.b: %x\n", &(y.b) );
    return y;
}

int main()
{
    X xxx = returnStruct();
    printf( "xxx.b: %d\n", xxx.b );
    printf( "address of xxx: %x\n", &xxx );
    printf( "address of xxx.b: %x\n", &(xxx.b) );
    return 0;
}

놀랐다. pointer만 불친절하게 return될 줄 알았거든.