2015-03-31 34 views
1
#include<stdio.h> 
#include<string.h> 
void main() 
{ 
int entry,i; 
printf("\nPlease indicate the number of records you want to enter :\n"); 
scanf("%d",entry); 
char ent[entry][100000]; 
printf("\nPlease input records of students (enter a new line after each record), with following format first name last name score \n"); 
for(i=0;i<entry;i++) 
    { 
    gets(ent[i]); 
    printf("%s",ent[i]); 
    } 
} 

以下是接受學生數據,名字姓氏然後得分的代碼。爲什麼我會收到分段錯誤?

+5

'scanf函數使用malloc得到一個數組時,你可以不知道數組的長度(「%d」,&entry);'你錯過了&符號。 – JS1 2015-03-31 02:49:39

+0

此外,大多數系統對本地陣列的大小有相當低的限制,您可能會超過它。你應該使用'malloc()'來代替。 – Barmar 2015-03-31 02:51:52

+0

@ JS1即使在處理&符號後仍存在錯誤。謝謝 – 2015-03-31 02:52:08

回答

2

main應該返回int而不是void

int main(void) { 
    /* ... */ 
} 

scanf("%d",entry); 

scanf預計對應於"%d"格式說明符的參數是一個int *。然而,你的論點是int。也許你的意思是這樣的:

scanf("%d",&entry); 

關於這一點,你應該檢查scanf返回值。對於你所知道的,用戶沒有輸入任何數字。

​​

事實上,這仍然允許用戶輸入一個負數。你有沒有看過一系列負數項目?覺得奇怪,我也一樣......我想size_t會比int(,因此,你需要使用%zu格式說明)更合適的類型......

最後但並非最不重要的,gets已被棄用,因爲它無法防止用戶溢出緩衝區,這可能導致段錯誤。


#include <stdio.h> 
#include <string.h> 
int main(void) 
{ 
    size_t entry; 
    printf("\nPlease indicate the number of records you want to enter :\n"); 
    if (scanf("%zu",&entry) != 1) 
    { 
     exit(0); 
    } 

    char ent[entry][100000]; 
    printf("\nPlease input records of students (enter a new line after each record), with following format first name last name score \n"); 
    for(size_t i=0; i<entry; i++) 
    { 
     fgets(ent[i], sizeof ent[i], stdin); 
     printf("%s",ent[i]); 
    } 
} 
0

的錯誤是在scanf使用scanf("%d",&entry)代替scanf("%d",entry);

建議:使用int作爲返回類型爲main

+0

感謝大家的幫助:) – 2015-03-31 02:54:40

+0

難道你不想添加一些關於'gets()'的東西嗎? – 2015-03-31 11:30:06

1
  1. 你應該使用int main()代替void main
  2. 時你用你sh scanf("%d",&entry)而不是scanf("%d",entry),scanf需要的是一個地址。
  3. 你不應該使用gets(),很危險,儘量fgets()
1
scanf("%d",entry);  //scanf("%d",&entry) 
char ent[entry][100000]; //error 

你應該在編譯時間

相關問題