2010-04-27 5 views
4

이 아마 이제까지 C 프로그래밍 언어에서 가장 쉬운 질문 중 하나입니다 ... {}을 (를) 사용하여 포인터 구조를 어떻게 선언 할 수 있습니까?

나는 다음과 같은 코드를 가지고 :
typedef struct node 
{ 
    int data; 
    struct node * after; 
    struct node * before; 
}node; 

struct node head = {10,&head,&head}; 

내가 머리로 할 수있는 방법 * 머리 [그것을 만들 수 있습니까 포인터]를 사용할 수 있고 여전히 '{}'[{10, & head, & head}]를 사용하여 head의 인스턴스를 선언하고 여전히 전역 범위에 두도록 할 수 있습니까? 예를 들어

:

//not legal!!! 
struct node *head = {10,&head,&head}; 

답변

7

해결 방법 1 : struct node *head = {10, head, head}만큼 간단

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


typedef struct node 
{ 
    int data; 
    struct node * after; 
    struct node * before; 
}node; 
int main() { 

    struct node* head = (struct node *)malloc(sizeof(struct node)); //allocate memory 
    *head = (struct node){10,head,head}; //cast to struct node 

    printf("%d", head->data); 

} 

뭔가 당신이 구조체합니다 (INT와 두 개의 포인터)의 메모리를 할당하지 않았기 때문에 작동하지 않을.

해결 방법 2 :

이 범위를 벗어나 이동합니다
#include <stdlib.h> 
#include <stdio.h> 


typedef struct node 
{ 
    int data; 
    struct node * after; 
    struct node * before; 
}node; 
int main() { 

    struct node* head = &(struct node){10,head,head}; 

    printf("%d", head->data); 

} 

- 솔루션 1이 이유 우수하고 링크 목록을 작성하고 있기 때문에, 나는 당신을 믿지 필요 힙 할당 된 메모리를 - 스택이 할당되지 않았습니다.

+0

즉, 전역 범위에서 메모리를 할당 할 수 없습니까? –

0

당신은 머리 포인터 할 수 있습니다,하지만 당신은 함수에서 초기화해야합니다.

struct node head_node; 
struct node *head = &head_node; 

void 
initialize() { 
    *head = {10,&head_node,&head_node}; 
} 

헤드 범위를 전역 범위에서 직접 초기화 할 수있는 방법은 없습니다.

관련 문제