2013-02-12 3 views
0

는 다음 코드분할 고장 난 C에 새로운 오전 및

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

typedef struct 
{ 
    int name1; 
}check1; 
typedef struct 
{ 
    int name2; 
}check2; 

int main() 
{ 
    check1 *test1; 
    check2 *test2; 
    test1->name1=1; 
    test2->name2=2; 
    return 0; 
} 

을 썼다 : -

Program received signal SIGSEGV, Segmentation fault. 
0x000000000040045e in main() 

어떤 이유 일 수 있습니까 ???

감사합니다.

답변

3

두 포인터를 선언했지만 포인터를 가리킬 메모리를 할당하지 않았습니다. 포인터가 잘못된 메모리를 가리키고 있습니다.

이 시도 :

check1 *test1 = malloc(sizeof(*test1)); 
if (test1 == NULL) 
    // report failure 

check2 *test2 = malloc(sizeof(*test2)); 
if (test2 == NULL) 
    // report failure 
0

또한 스택에 변수를 선언하고 포인터에 자신의 주소를 할당 할 수 있습니다.

check checka; 
check* pcheck = &checka; 
printf("%i",pcheck->name1); 
관련 문제