[英]Program received signal SIGSEGV, Segmentation fault. # C LANGUAGE#
我有一个程序接收到的信号 SIGSEGV,分段错误。 我真的不知道如何解决它,它说问题出在“scanf(” %s “,& t[i].poste);”这一行
#include <stdio.h>
#include <stdlib.h>
typedef struct { int d,m,y; } dtype ;
typedef struct { char nom[10]; char prenom[10] ; char poste[00]; dtype date ; } LEM ;
int main()
{
int n,i,j;
printf("Liste des employes\n");
printf("\n nombre d'employes : ");
scanf("%d",&n);
LEM t[n];
for(i=1;i<=n;i++)
{
printf("\nemploye number %d :",i);
printf("\n nom : ");
scanf("%s",&t[i].nom);
printf("\n prenom : ");
scanf("%s",&t[i].prenom);
printf("\n poste : ");
scanf("%s",&t[i].poste);
printf("\n date de recrutement : ");
printf("\n day : ");
scanf("%d",&t[i].date.d);
printf("\n month : ");
scanf("%d",&t[i].date.m);
printf("\n year : ");
scanf("%d",&t[i].date.y);
}
for(i=1;i<=n;i++)
{
printf("nom : %s \t",t[i].nom);
printf("prenom : %s \t",t[i].prenom);
printf("poste : %s \t",t[i].poste);
printf("date de rec : %d/%d/%d \t",t[i].date.d , t[i].date.m ,t[i].date.y);
}
}
如果您的代码正确粘贴,则您已将poste
设置为 0 大小(在行typedef struct { char nom[10]; char prenom[10]; char poste[00]; dtype date; } LEM;
中)。 也许您的意思是10
而不是00
?
您for
循环应该从0
开始并在i
小于n
时结束,因为数组索引从 0 开始。在您的循环中,您首先要跳过第一个元素,然后在最后一次迭代中,您将访问无效的 memory 并且您正在获得分段过错。
要修改的另一件事是您如何处理scanf
-s。 将某些内容读入数组时,您应该检查要放入数组中的内容是否合适。 如果向程序传递一个大于 9 个字符的字符串会发生什么? 它可能会溢出数组并导致另一个分段错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.