2013-09-07 3 views
0

, 그래서구조체의 구조체를 할당하는 방법은 무엇입니까? 그래서

#include <stdio.h> 
#include <string.h> 

struct 
{ 
    int n, o, p; 
    struct 
    { 
     int a, b, c; 
    }Str2; 
}Str1; 

main() 
{ 
    struct Str1.Str2 *x (Str1.Str2*)malloc(sizeof(struct Str1.Str2*)); 

    x->a = 10; 
} 

... 내가 .. 다른 구조체의 내부 구조체를 가지고 내가 그 구조체의 malloc 수있는 방법을 알고 whant, 나는이 작동하지 않는 것을 시도하지만 .. 어떻게 이것을 만들 수 있습니까, 아니면 더 나은 모든 구조체를 할당 할 수 있습니까? 당신이 원하는대로 그럼 당신은 개별적으로 할당 할 수

typedef struct 
{ 
    int a, b, c; 
}Str2; 

typedef struct 
{ 
    int n, o, p; 
    Str2 s2; 
}Str1; 

: 같은 일을 선언하지 왜

답변

1

. 예를 들어 : 구문이 방법 꺼져 있도록

Str2 *str2 = (Str2*)malloc(sizeof(Str2)); 
Str1 *str1 = (Str1*)malloc(sizeof(Str1)); 
s1->s2.a = 0; // assign 0 to the a member of the inner Str2 of str1. 
+0

Ooook, 및이를 사용하는 ?? .. 구조체 (PS)와 복수의 랜덤 * X = (구조체 (PS)와 복수의 랜덤 *)의 malloc (sizeof 연산자 (구조체 (PS)와 복수의 랜덤 *)). 그리고 X-> s2.a = 10? – Alexandre

1

Str1Str2, 당신은 선언 익명 struct의의 개체입니다. typedef를 잊어 버렸습니까?

//declares a single object Str1 of an anonymous struct 
struct 
{ 
}Str1; 

//defines a new type - struct Str1Type 
typedef struct 
{ 
}Str1Type; 
3

Str1을 할당하면 Str2가 자동으로 할당됩니다. 내 시스템에서, Str1에 대한 sizeof는 24이며 이것은 6 ints의 크기와 같습니다. 이 시도 :

typedef struct { 
int n; 
int o; 
int p; 
struct { 
     int a; 
     int b; 
     int c; 
     }Str2; 
}Str1; 

main() 
{ 
    Str1 *x = (Str1 *)malloc(sizeof(Str1)); 
    x->Str2.a = 10; 
    printf("sizeof(Str1) %d\n", (int)sizeof(Str1)); 
    printf("value of a: %d\n", x->Str2.a); 
} 
1

struct 이름을 지정하려면, 당신은 당신이 특정 struct 참조 할 때 이제 struct Str1을 사용할 수 있습니다

struct Str1 
{ 
    ... 
}; 

를 사용합니다.

Str1으로 만 사용하려면 typedef (예 : typedef)을 사용해야합니다.

typedef struct tagStr1 
{ 
    ... 
} Str1; 

또는 typedef struct Str1 Str1; 우리는 struct Str1 선언의 첫 번째 유형이있는 경우.

은 (인스턴스 "유형의 변수"를 의미)없는 이름을 가진 struct의 인스턴스를 만들려면 이름이없는이 struct 이후

struct 
{ 
    ... 
} Instance; 

를, 그것은 어디서나 사용할 수 없습니다 그렇지 않으면 일반적으로 원하는 것이 아닙니다.

(C++ 반대) C에서

그렇게

typedef struct tagStr1 
{ 
    int a, b, c; 
    typedef struct tagStr2 
    { 
     int x, y, z; 
    } Str2; 
} Str1; 

가 컴파일되지 않습니다, 다른 내부에 또 다른 구조의 유형 정의를 새로운 형태의 구조를 정의 할 수 없습니다. 우리는이에 코드를 변경하는 경우

:

typedef struct tagStr1 
{ 
    int a, b, c; 
    struct tagStr2 
    { 
     int x, y, z; 
    }; 
} Str1; 
typedef struct tagStr2 Str2; 

컴파일합니다 -하지만 적어도 GCC는 (은 기대하기 때문에 실제로의 회원을 가지고 싶었다 "구조체 tagStr2이 anythign을 선언하지 않는다"에 대한 경고를 제공 Str1 내부 struct tagStr2 입력

+0

oook 및 사용 : struct Str2 * x = (struct Str2 *) malloc (sizeof (struct Str2 *)); x-> x = 10; – Alexandre

+0

'sizeof (struct Str2 *)'가 아닙니다 - 포인터 만위한 공간을 만듭니다. 'sizeof (struct Str2);' –

관련 문제