2015-03-31 69 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 

你应该在编译时间

相关问题