2013-02-12 95 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; 
} 

當我執行它,它給我的錯誤:

$ gcc test1.c 
$ ./a.out 
Memory fault 

在GDB: -

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);