2013-08-13 3 views
1

구조체를 편집하는 함수에 내 구조체에 대한 포인터를 전달하려고합니다.Typedef 구조체 포인터

이 작동하지 않습니다

typedef struct{ 

    unsigned char x; 
    unsigned char y; 
    float z; 


}C_TypeDef; 


C_TypeDef *ptr_struct; //This is the part that I change to get it to work. 


void print_TypeDef(C_TypeDef *report, unsigned char x_data) 
{ 

    report->x = x_data; 
    printf("x is equal to %d", report->x); 


} 

int main(void) 
{ 

    print_TypeDef(ptr_struct,0x23); 
    getchar(); 

} 

을 지금 내가이 포인터가 여전히 작동하지 않습니다되어 선언 부분을 변경하는 경우. 작동하지 않음 :

C_TypeDef x_struct; 
C_TypeDef *ptr_struct; 
ptr_struct = &x_struct; 

그러나이 코드를 변경하면 작동합니다!

C_TypeDef x_struct; 
C_TypeDef *ptr_struct = &x_struct; 

제 질문은 왜 처음 두 가지가 작동하지 않는 이유입니까? 이것은 나를 괴롭 히고있다.

답변

2

첫 번째 버전의 문제는 ptr_struct이 가리키는 메모리를 할당하지 않았기 때문에 일반적으로 세그먼트 오류가 발생한다는 것입니다. 세 번째 버전이 작동하는 이유

C_TypeDef x_struct; 
C_TypeDef *ptr_struct = &x_struct; 

:이 고정되어 있습니다. 그렇다면 두 번째 버전의 문제점은 무엇입니까? 당신이 어떤 기능을 외부에서 전역 변수를 할당 할 수 있기 때문에, 당신은 세 번째 버전에서 무슨 짓을했는지처럼 초기화하거나 같은 일부 기능에 할당해야 main에서 :

C_TypeDef x_struct; 
C_TypeDef *ptr_struct; 

//omit other parts 

int main(void) 
{ 
    ptr_struct = &x_struct; //Here assign the pointer a value 
    print_TypeDef(ptr_struct,0x23); 
    getchar(); 
} 
0

의 첫 번째 버전 구조체에 대한 포인터 유형을 작성 했으므로 코드가 작동하지 않고 실제 주소가 할당되지 않았습니다. 그러나 노력하면 문

C_TypeDef x_struct; 
C_TypeDef *ptr_struct; 

완벽하게 정확하기 때문에 두 번째 버전이 작동하지

print_TypeDef(ptr_struct,0x23);\\here ptr_struct is not pointing to any instance of the      structure. 

호출 기능에 액세스하지만, 변수에 값을 할당하는 다음 문에 있지하기 가능한 모든 기능 외부. 덧붙여

C_TypeDef x_struct;\\correct, creating a instance of struct type 
C_TypeDef *ptr_struct;\\correct, creating a pointer to an structure 
ptr_struct = &x_struct;\\wrong, as this statement is possible only inside a function. 

하는 코드가 대신이

C_TypeDef x_struct; 

에 의해 메인에서 잘 작동합니다, 구조 인스턴스와 해당 인스턴스의 포인터 모두를 생성 할 필요가 작동하려면,이 같은 함수를 호출 ,

int main(void) 
{ 

    print_TypeDef(&x_struct,0x23); 
    getchar(); 

}