[英]scanf taking value of a struct element giving seg fault in C linux
我的scanf語句給段錯誤。 你能告訴我為什么嗎?
typedef struct message1
{
int call_id1;
int lac;
long int attribute;
int conn_id;
struct message1 *next1;
}M1;
M1 *last=NULL;
main()
{
printf("\nEnter Call Id\t");
scanf("%d",&last->call_id1);
}
您試圖讀入未分配內存的結構
加
M1 * last = malloc(sizeof(struct message1)); //在全球空間
要么
最后= malloc(sizeof(struct message1)); //在主函數中
因為您使用NULL初始化了結構指針。
M1 last;
足夠。
無需提供任何指針。 如果您希望將其用作指針,請使用malloc
M1 *last;
last = malloc(sizeof(M1));
顯然...未初始化為適當的值:
M1 *last=NULL;
應該
M1 *last= (M1*)malloc(sizeof(M1));
您尚未為結構M1
分配內存,並嘗試訪問其內存內容,這是分段錯誤的原因,
動態分配內存, M1 *last = malloc(sizeof(M1));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.