2016-11-15 96 views
2

在運行代碼時得到分段轉儲錯誤,但它會正確編譯。 當我運行該程序時,它要求我輸入 向名稱數組輸入值後,會導致分段錯誤。 請幫助我使用無錯解決方案。C中出現錯誤「分段錯誤(核心轉儲)」

#include<stdio.h> 

struct book 
{ 
char name[20]; 
char author[20]; 
int price; 
}; 

struct pages 
{ 
int page; 
struct book b1; 
} *p; 

int main() 
{ 
printf("\nEnter the book name , author , price, pages\n"); 
scanf("%s %s %d %d",p->b1.name,p->b1.author,&p->b1.price,&p->page); 

printf("The entered values are\n"); 

printf("The name of book=%s\n",p->b1.name); 
printf("The author of book=%s\n",p->b1.author); 
printf("The price of book=%d\n",p->b1.price); 
printf("The pages of book=%d\n",p->page); 



return 0; 


} 

回答

3

你還沒有爲p分配的內存。添加代碼爲p分配內存並在從main返回之前釋放該內存。使用

int main() 
{ 
    p = malloc(sizeof(*p)); 

    printf("\nEnter the book name , author , price, pages\n"); 
    scanf("%s %s %d %d",p->b1.name,p->b1.author,&p->b1.price,&p->page); 

    ... 

    free(p); 
    return 0; 
} 
+0

它'p'是一個指向結構的指針,當我使用malloc分配內存後,但如果我使用'p'作爲結構'頁'的變量(不是指針),那麼我不' t需要使用malloc分配內存。爲什麼? –

+0

@AuuragVishwa,那麼'p'是一個對象。對象的內存由運行時環境創建。使用'malloc'不需要爲定義爲對象的變量創建內存。 –